<?php

/**
 * 73YC 会员中心
 * ============================================================================
 * * 版权所有 20013-* 梅州络客网络科技有限公司，并保留所有权利。
 * 网站地址: http://www.alork.com；
 * ----------------------------------------------------------------------------
 * 这不是一个自由软件！您只能在不用于商业目的的前提下对程序代码进行修改和
 * 使用；不允许对程序代码以任何形式任何目的的再发布。
 * ============================================================================
 * $Author: liubo $
 * $Id: index.php 17217 2013-10-19 06:29:08Z liubo $
*/


define('IN_ECS', true);

require(dirname(__FILE__) . '/includes/init.php');
/* 载入语言文件 */
require_once(ROOT_PATH . 'languages/' .$_CFG['lang']. '/user.php');

$user_id = $_SESSION['user_id'];
if(!empty($user_id)){
    $sql = 'SELECT agent_rank FROM '.$ecs->table('users')."WHERE user_id = ".$user_id;
    $agent_rank = $db->getOne($sql);
}
$smarty->assign('agent_rank', $agent_rank);
$action  = isset($_REQUEST['act']) ? trim($_REQUEST['act']) : 'default';
/*4.1活动*/
$times = time();
if ($times>1427860800&&$times<1428595200) {
$smarty->assign('num_4_1', 1);
}

$affiliate = unserialize($GLOBALS['_CFG']['affiliate']);
$smarty->assign('affiliate', $affiliate);
$back_act='';

// 不需要登录的操作或自己验证是否登录（如ajax处理）的act
$not_login_arr =
array('login','complete',  'change_password', 'detect_captcha','act_login','register','act_register','act_edit_password','get_password','send_pwd_email','password', 'signin', 'add_tag', 'collect', 'return_to_cart', 'logout', 'email_list', 'validate_email', 'send_hash_mail', 'order_query', 'is_registered', 'check_email','clear_history','qpassword_name', 'get_email', 'check_answer','order_return','bindingMobile','ajax_register','rp_validate_mobile','ajax_change_password','email_change_password', 'registerCaptcha','send_reset_captcha');

/* 显示页面的action列表 */
$ui_arr = array('dellookat','complete','change_password','detect_captcha','join_list','join_detail','register', 'login', 'profile', 'profile_pass','my_recommend', 'my_recommend_action','my_distributor' , 'distributor_detailed' ,'user_withdraw' , 'order_list', 'order_detail', 'address_list', 'collection_list',
'message_list', 'tag_list', 'get_password', 'reset_password', 'booking_list', 'add_booking', 'account_raply','message',
'account_deposit', 'account_log', 'account_detail', 'act_account', 'pay', 'default', 'bonus', 'group_buy', 'group_buy_detail', 'affiliate', 'comment_list','validate_email', 'guadanle', 'add_cart', 'track_packages', 'coupon', 'transform_points','qpassword_name', 'get_email', 'check_answer' ,'void_join', 'mobile_validated', 'validated_mobile','sale_service','sale_service_form','done','error', 'sale_list','sale_service_handle',"sale_detail");

/* 未登录处理 */
if (empty($_SESSION['user_id']))
{
    if (!in_array($action, $not_login_arr))
    {
        if (in_array($action, $ui_arr))
        {
            /* 如果需要登录,并是显示页面的操作，记录当前操作，用于登录后跳转到相应操作
            if ($action == 'login')
            {
                if (isset($_REQUEST['back_act']))
                {
                    $back_act = trim($_REQUEST['back_act']);
                }
            }
            else
            {}*/
            if (!empty($_SERVER['QUERY_STRING']))
            {
                $back_act = 'user.php?' . strip_tags($_SERVER['QUERY_STRING']);
            }
            $action = 'login';
        }
        else
        {
            //未登录提交数据。非正常途径提交数据！
            die($_LANG['require_login']);
        }
    }
}
/* 如果是显示页面，对页面进行相应赋值 */
if (in_array($action, $ui_arr))
{

    assign_template();//通用赋值
    $position = assign_ur_here();
    $smarty->assign('page_title',      $position['title']);    // 页面标题
    $smarty->assign('keywords',        htmlspecialchars($_CFG['shop_keywords']));
    $smarty->assign('description',     htmlspecialchars($_CFG['shop_desc']));
    $smarty->assign('data_dir',   DATA_DIR);   // 数据目录
    $smarty->assign('action',     $action);
    $smarty->assign('lang',       $_LANG);
    if (isset($_REQUEST['back_act'])) {
        $back_act = trim($_REQUEST['back_act']);
        $smarty->assign('back_act',       $back_act);
    }
    include_once(ROOT_PATH .'includes/lib_clips.php');


}

//用户中心欢迎页
if ($action == 'default')
{

    include_once(ROOT_PATH . 'includes/lib_payment.php');
    include_once(ROOT_PATH .'includes/lib_clips.php');
    include_once(ROOT_PATH . 'includes/lib_transaction.php');
    if ($rank = get_rank_info())
    {
        $smarty->assign('rank_name', sprintf($_LANG['your_level'], $rank['rank_name']));
        if (!empty($rank['next_rank_name']))
        {
            $smarty->assign('next_rank_name', sprintf($_LANG['next_level'], $rank['next_rank'] ,$rank['next_rank_name']));
        }
    }
    $orders = get_user_orders($user_id, "6", "0");

    foreach ($orders as $key => $value) {
        $nums=0;
        $num=order_goods($value["order_id"]);
        foreach ($num as $keys => $values) {
           $nums=$nums+$values["goods_number"];
        }
         $orders[$key]["count"]=$nums;
         $orders[$key]["son"]=$num;
    }

    $get_this_month_goods = get_this_month_goods($user_id);
    $get_this_month_percentage = get_this_month_percentage($user_id);

    $smarty->assign('get_this_month_goods', $get_this_month_goods);//当月消费记录
    $smarty->assign('get_this_month_percentage', $get_this_month_percentage);//考上美院成功率
    $smarty->assign('collection_list', get_collection_goods($user_id, '6', '0'));//收藏商品
    $smarty->assign('once_list', get_once_goods($user_id, '32', '0'));//买过的商品
    $smarty->assign('orders', $orders);//订单列表
    $smarty->assign('is_look_num', get_user_join_look($user_id));//合单数量
    $smarty->display('user_clips.dwt');
}

/* 显示会员注册界面 */
if ($action == 'register')
{
    if ((!isset($back_act)||empty($back_act)) && isset($GLOBALS['_SERVER']['HTTP_REFERER']))
    {
        $back_act = strpos($GLOBALS['_SERVER']['HTTP_REFERER'], 'user.php') ? './index.php' : $GLOBALS['_SERVER']['HTTP_REFERER'];
    }

    /* 取出注册扩展字段 */
    $sql = 'SELECT * FROM ' . $ecs->table('reg_fields') . ' WHERE type < 2 AND display = 1 ORDER BY dis_order, id';
    $extend_info_list = $db->getAll($sql);
    $smarty->assign('extend_info_list', $extend_info_list);

    /* 验证码相关设置 */
    if ((intval($_CFG['captcha']) & CAPTCHA_REGISTER) && gd_version() > 0)
    {
        $smarty->assign('enabled_captcha', 1);
        $smarty->assign('rand',            mt_rand());
    }

    /* 密码提示问题 */
    $smarty->assign('passwd_questions', $_LANG['passwd_questions']);
    /* 增加是否关闭注册 */
    $smarty->assign('shop_reg_closed', $_CFG['shop_reg_closed']);
    $smarty->assign('back_act', $back_act);
    $smarty->display('register/register.dwt');
}



/*发送找回密码的验证码*/
elseif ($action == 'send_reset_captcha')
{
        include_once('includes/cls_json.php');
        $json = new JSON;
        include_once(ROOT_PATH . 'includes/lib_passport.php');
        $username = isset($_POST['username']) ? trim($_POST['username']) : '';
        $return   = array('error' => 0, 'content' => '','message' => '');
        //判断用户名是否正确
        if(empty($username)){
            $return['error']   = 501;
            $return['message'] = '请输入手机号/邮箱';
        }else if((!preg_match("/^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/",$username))&&(!preg_match("/^1[3|4|5|8][0-9]\d{8}$/",$username))){
            $return['error']   = 504;
            $return['message'] = '请输入正确的手机号或邮箱';
        }

        /*如果用户输入验证邮箱发送邮箱验证*/
        if(preg_match("/^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/",$username)){
            $sql = "SELECT user_id ,user_name FROM ".$ecs->table('users')." WHERE email = '$username' OR user_name = '$username' ";
            $user_info = $db->getRow($sql);
            if (empty($user_info)) {
                $return['error']   = 510;
                $return['message'] = '用户不存在';
                die($json->encode($return));
            }

           $user_info['add_time'] = time();
           $user_info['code'] = rand('10000000','99999999');
           /*将重置密钥写入用户表*/
            $sql = "UPDATE ". $GLOBALS['ecs']->table('users') . " SET captcha = '".$user_info['code']."' WHERE user_id = '".$user_info['user_id']."'";
            $db->query($sql);
           /*发送重置密码邮件*/
           send_retrieve_hash($user_info['user_name'],$username,$user_info);
           $smarty->assign('email',$username);
           $smarty->assign('action','resetEmail');

        }

        /*如果用户输入手机号发送手机验证*/
        if(preg_match("/^1[3|4|5|8][0-9]\d{8}$/",$username)){
            $sql = "SELECT user_id FROM ".$ecs->table('users')." WHERE mobile_phone = '$username' OR user_name = '$username' ";
            $user_id = $db->getOne($sql);
            if (empty($user_id)) {
                $return['error']   = 504;
                $return['message'] = '用户不存在';
                die($json->encode($return));
            }
            require(dirname(__FILE__) . '/plugins/sms2.php'); //引入接口文件
            $username = intval($username);
            $code = rand('100000','999999');
            $text = "【鸡蛋美术】您的验证码是:" . $code."该验证码用于用户重置密码请勿告诉他人";//短信内容
            $data = send_sms($text, $username);
            $data = get_object_vars(json_decode($data));
            if($data['msg'] == 'OK'){
                $_SESSION['resetCaptcha'] = $code;
                $_SESSION['user_id'.$code] = $user_id;
            }

            $smarty->assign('mobile',$username);
            $smarty->assign('action','resetCaptcha');
            $return['message'] = "请输入手机验证完成密码重置";
        }
        $return['error']   = 0;
        $return['content'] = $smarty->fetch('library/ajax_loading.lbi');
        die($json->encode($return));

}
/* 处理 ajax 的注册请求 */
elseif ($action == 'ajax_register')
{
    include_once('includes/cls_json.php');
    $json = new JSON;
        include_once(ROOT_PATH . 'includes/lib_passport.php');
        $username = isset($_POST['username']) ? trim($_POST['username']) : '';
        $password = isset($_POST['password']) ? trim($_POST['password']) : '';
        if (!empty($_POST['recommend_mobile'])) {
            /*查询用户是否存在*/
            $mobile_phone = $_POST['recommend_mobile'];
            $sql = 'SELECT user_id FROM '.$ecs->table('users')."WHERE mobile_phone = '".$mobile_phone."' AND agent_rank = '1'";
            $uid = $db->getOne($sql);
            $parentUid = $uid;
        }
        $checked_agreement = isset($_POST['checked_agreement']) ? trim($_POST['checked_agreement']) : '';
        $return   = array('error' => 0, 'content' => '','message' => '');
        //判断用户名是否正确
        if(empty($username)){
            $return['error']   = 501;
            $return['message'] = '请输入手机号/邮箱';
        }else if((!preg_match("/^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/",$username))&&(!preg_match("/^1[3|4|5|8][0-9]\d{8}$/",$username))){
            $return['error']   = 504;
            $return['message'] = '请输入正确的手机号或邮箱';
        }
        //判断密码是否符合要求
        if (strlen($password) == 0){
            $return['error']   = 502;
            $return['message'] = '登录密码不能为空';
        }else if (strlen($password) < 6){
            $return['error']   = 505;
            $return['message'] = '登录密码不能少于 6 个字符';
        }
        if (strpos($password, ' ') > 0){
            $return['error']   = 505;
            $return['message'] = '密码中不能包含空格';
        }

        /* 检验用户是否可以注册 */
        if ($user->check_user($username) || admin_registered($username))
        {
            $return['error']   = 1;
            $return['message'] = "已被注册使用，请重新输入";
            die($json->encode($return));
        }

        /*将数据存入session*/
        $_SESSION['registerUsername']=$username;
        $_SESSION['registerPassword']=$password;
        $_SESSION['registerParentUid']=$parentUid;

        if(preg_match("/^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/",$username)){
           $time=time();
           $user_info = array('username' => $username, 'password'=>$password,'add_time'=>$time);
           /*发送注册邮件*/
           send_regiter_hash($username,$user_info);
            // 向用户发送验证码
            // send_captcha($username,$code);
            $smarty->assign('username',$username);
            $smarty->assign('action','emailRegister');
        }
        if(preg_match("/^1[3|4|5|8][0-9]\d{8}$/",$username)){
            $smarty->assign('username',$username);
            $smarty->assign('action','mobileRegister');
        }
        $return['error']   = 0;
        $return['message'] = "请输入手机验证完成注册";
        $return['content'] = $smarty->fetch('library/ajax_loading.lbi');
        die($json->encode($return));
}

/* 验证用户注册邮件 */
elseif ($action == 'validate_email')
{
    $hash = empty($_GET['hash']) ? '' : trim($_GET['hash']);

    if ($hash)
    {
        include_once(ROOT_PATH . 'includes/lib_passport.php');
        $data = register_hash('decode', $hash);
        /*判断数据是否为空*/
        if (empty($data->username)||empty($data->password)||empty($data->add_time)||((time()-$data->add_time)>3600)) {
            $smarty->assign('action','fail');
            $smarty->display('register_result.dwt');
           exit();
        }else{
            /*查询用户是否存在*/
            $sql = 'SELECT count(*) FROM '.$ecs->table('users')."WHERE email = '".$data->username."' OR user_name = '".$data->username."'";
            $id = $db->getOne($sql);
            if ($id) {
                $smarty->assign('action','fail');
                $smarty->display('email_result.dwt');
                exit();
            }

            if (register($data->username, $data->password) !== false)
            {
                require_once(ROOT_PATH.'/plugins/ip/ip.php');
                $ip = new ip();
                $addr = $ip->ip2addr(real_ip());
                $errorlog = (
                    time()."\t".
                    $username."\t".
                    '0'."\t".
                    real_ip()."\t".
                    $addr['country']."\t".
                    'PC'."\t".
                    get_user_browser()."\t".
                    "注册");
                writelog('cplogs', $errorlog);
                $sql = "UPDATE ". $GLOBALS['ecs']->table('users') . " SET email = '$username',is_validated = '1' WHERE user_id = " . $_SESSION['user_id'];
                $GLOBALS['db']->query($sql);
                $smarty->assign('action','success');
                $smarty->display('email_result.dwt');
                exit();
            }
            else
            {
                require_once(ROOT_PATH.'/plugins/ip/ip.php');
                $ip = new ip();
                $addr = $ip->ip2addr(real_ip());
                $errorlog = (
                    time()."\t".
                    $username."\t".
                    '0'."\t".
                    real_ip()."\t".
                    $addr['country']."\t".
                    'PC'."\t".
                    get_user_browser()."\t".
                    "注册失败");
                writelog('cplogs', $errorlog);
                $smarty->assign('action','fail');
                $smarty->display('email_result.dwt');
                exit();
            }
        }
    }else{
        /*失败页面*/
        $smarty->assign('action','fail');
        $smarty->display('email_result.dwt');
    }
}

/* 验证用户注册用户名是否可以注册 */
elseif ($action == 'is_registered')
{
    include_once(ROOT_PATH . 'includes/lib_passport.php');

    $username = trim($_GET['username']);
    $username = json_str_iconv($username);

    if ($user->check_user($username) || admin_registered($username))
    {
        echo 'false';
    }
    else
    {
        echo 'true';
    }
}

/* 验证用户邮箱地址是否被注册 */
elseif($action == 'check_email')
{
    $email = trim($_GET['email']);
    if ($user->check_email($email))
    {
        echo 'false';
    }
    else
    {
        echo 'ok';
    }
}
/* 用户登录界面 */
elseif ($action == 'login')
{
    if (empty($back_act))
    {
        if (empty($back_act) && isset($GLOBALS['_SERVER']['HTTP_REFERER']))
        {
            $back_act = strpos($GLOBALS['_SERVER']['HTTP_REFERER'], 'user.php') ? './index.php' : $GLOBALS['_SERVER']['HTTP_REFERER'];
        }
        else
        {
            $back_act = 'user.php';
        }

    }


    $captcha = intval($_CFG['captcha']);
    if (($captcha & CAPTCHA_LOGIN) && (!($captcha & CAPTCHA_LOGIN_FAIL) || (($captcha & CAPTCHA_LOGIN_FAIL) && $_SESSION['login_fail'] > 2)) && gd_version() > 0)
    {
        $GLOBALS['smarty']->assign('enabled_captcha', 1);
        $GLOBALS['smarty']->assign('rand', mt_rand());
    }

    $smarty->assign('back_act', $back_act);
    $smarty->display('login/login.dwt');
}


/* 处理 ajax 的登录请求 */
elseif ($action == 'signin')
{
    include_once('includes/cls_json.php');
    $json = new JSON;

    $username = !empty($_POST['username']) ? json_str_iconv(trim($_POST['username'])) : '';
    $password = !empty($_POST['password']) ? trim($_POST['password']) : '';
    $captcha = !empty($_POST['captcha']) ? json_str_iconv(trim($_POST['captcha'])) : '';
    $return   = array('error' => 0, 'content' => '','message'=>'');

    if(!$username){
        $return['error']   = 501;
        $return['message'] = '请输入用户名！';
        die($json->encode($return));
    }
    if(!$password){
        $return['error']   = 502;
        $return['message'] = '请输入密码！';
        die($json->encode($return));
    }

    $captcha = intval($_CFG['captcha']);
    if (($captcha & CAPTCHA_LOGIN) && (!($captcha & CAPTCHA_LOGIN_FAIL) || (($captcha & CAPTCHA_LOGIN_FAIL) && $_SESSION['login_fail'] > 2)) && gd_version() > 0)
    {
        if (empty($captcha))
        {
            $return['error']   = 508;
            $return['message'] = $_LANG['invalid_captcha'];
            die($json->encode($return));
        }

        /* 检查验证码 */
        include_once('includes/cls_captcha.php');

        $validator = new captcha();
        $validator->session_word = 'captcha_login';
        if (!$validator->check_word($_POST['captcha']))
        {
            $return['error']   = 506;
            $return['message'] = $_LANG['invalid_captcha'];
            die($json->encode($return));
        }
    }

    if ($user->login($username, $password,$_POST['remember']))
    {

        /* 查询用户是否已经验证手机 */
        $sql = "SELECT `mobile_phone`, `is_mobile_validated` FROM " . $GLOBALS['ecs']->table('users') . " WHERE user_id =".$_SESSION['user_id']." AND is_mobile_validated = 0";
        $is_mobile_validated = $db->getRow($sql);

        /*如果未绑定返回绑定弹框*/
        if (!empty($is_mobile_validated)) {
            $return['message'] ='为了你的账号安全请绑定手机';
            $smarty->assign('action', 'binding_mobile');
            $return['content'] = $smarty->fetch('library/ajax_loading.lbi');
        }else{
            $return['message'] ='登录成功';
        }

        require_once(ROOT_PATH.'/plugins/ip/ip.php');
        $ip = new ip();
        $addr = $ip->ip2addr(real_ip());
        $errorlog = (
            time()."\t".
            $username."\t".
            '0'."\t".
            real_ip()."\t".
            $addr['country']."\t".
            'PC'."\t".
            get_user_browser()."\t".
            "登录");
        writelog('cplogs', $errorlog);
        update_user_info();  //更新用户信息
        $smarty->assign('user_info', get_user_info());

    }
    else
    {

        require_once(ROOT_PATH.'/plugins/ip/ip.php');
        $ip = new ip();
        $addr = $ip->ip2addr(real_ip());
        $errorlog = (
            time()."\t".
            $username."\t".
            '0'."\t".
            real_ip()."\t".
            $addr['country']."\t".
            'PC'."\t".
            get_user_browser()."\t".
            "登录失败");

        writelog('cplogs', $errorlog);
        $return['error']   = 507;
        $return['message'] = '您输入的账号或密码不正确，请重新输入';
    }
    
    die($json->encode($return));
}

/* ajax验证码绑定手机 */
elseif ($action == 'bindingMobile') {
    include_once('includes/cls_json.php');
    $json = new JSON;
    $captcha_num =  !empty(is_numeric($_POST['captcha_num'])) ? intval(trim($_POST['captcha_num'])) : '';
    $mobile_num =  !empty(is_numeric($_POST['mobile_num'])) ? intval(trim($_POST['mobile_num'])) : '';
    $return = array('error' => 0,'message'=>'','content'=>'' );
    //判断验证码是否一样
    if($captcha_num == $_SESSION['mobileCaptcha']){
        $sql = "UPDATE " . $ecs->table('users') . " SET is_mobile_validated = '1', mobile_phone = '" . $mobile_num . "' WHERE user_id = '" . $_SESSION['user_id'] . "'";
        $db->query($sql);
        $return['message'] = "绑定成功";
        $smarty->assign('action','binding_success');
        $return['content'] = $smarty->fetch('library/ajax_loading.lbi');
    }else{
        $return['error'] = 506;
        $return['message'] = "验证码错误";
    }
    die($json->encode($return));
}
/*手机验证注册*/
elseif ($action == 'registerCaptcha') {
    include_once('includes/cls_json.php');
    $json = new JSON;
    $captcha_num =  !empty(is_numeric($_POST['captcha_num'])) ? intval(trim($_POST['captcha_num'])) : '';
    $mobile_num  =  !empty(is_numeric($_POST['mobile_num'])) ? intval(trim($_POST['mobile_num'])) : '';
    $username    =  !empty($_SESSION['registerUsername'])?$_SESSION['registerUsername']:'';
    $password    =  !empty($_SESSION['registerPassword'])?$_SESSION['registerPassword']:'';
    $parentUid    =  !empty($_SESSION['registerParentUid'])?$_SESSION['registerParentUid']:'0';
    $return = array('error' => 0,'message'=>'','content'=>'' );
    $_SESSION['registerCaptcha'] = $captcha_num = "123";
    //判断验证码是否一样
    if($captcha_num == $_SESSION['registerCaptcha']){
        if (empty($captcha_num)||empty($mobile_num)||empty($username)||empty($password)) {
            $return['message'] = "注册失败";
            $return['error'] = 555;
            die($json->encode($return));
        }
        include_once(ROOT_PATH . 'includes/lib_passport.php');
        if (register($username, $password) !== false)
        {
            require_once(ROOT_PATH.'/plugins/ip/ip.php');
            $ip = new ip();
            $addr = $ip->ip2addr(real_ip());
            $errorlog = (
                time()."\t".
                $username."\t".
                '0'."\t".
                real_ip()."\t".
                $addr['country']."\t".
                'PC'."\t".
                get_user_browser()."\t".
                "注册");
            writelog('cplogs', $errorlog);

            /*标记为绑定手机 和推荐人*/
            $agent2_time = $parentUid?time():0;
            $agent_rank  = $parentUid?2:100;
            $sql = "UPDATE ". $GLOBALS['ecs']->table('users') . " SET mobile_phone = '$mobile_num',is_mobile_validated = '1',parent_uid = '$parentUid', agent2_time = '$agent2_time' ,agent_rank = '$agent_rank' WHERE user_id = " . $_SESSION['user_id'];
            $db->query($sql);
            
            $smarty->assign('action','success_register');
            $return['error'] = 0;
            $return['message'] = "注册成功";
            $return['content'] = $smarty->fetch('library/ajax_loading.lbi');
        }
        else
        {
            require_once(ROOT_PATH.'/plugins/ip/ip.php');
            $ip = new ip();
            $addr = $ip->ip2addr(real_ip());
            $errorlog = (
                time()."\t".
                $username."\t".
                '0'."\t".
                real_ip()."\t".
                $addr['country']."\t".
                'PC'."\t".
                get_user_browser()."\t".
                "注册失败");
            writelog('cplogs', $errorlog);
            $return['error']   = 1;
            $return['message'] = "注册失败，请重新输入！";
        }
    }else{
        $return['message'] = "验证码错误";
        $return['error'] = 506;
        die($json->encode($return));
    }
    die($json->encode($return));
}





/* 退出会员中心 */
elseif ($action == 'logout')
{
    if ((!isset($back_act)|| empty($back_act)) && isset($GLOBALS['_SERVER']['HTTP_REFERER']))
    {
        $back_act = strpos($GLOBALS['_SERVER']['HTTP_REFERER'], 'user.php') ? './index.php' : $GLOBALS['_SERVER']['HTTP_REFERER'];
    }


    require_once(ROOT_PATH.'/plugins/ip/ip.php');
    $ip = new ip();
    $addr = $ip->ip2addr(real_ip());
    $errorlog = (
        time()."\t".
        $_SESSION['user_name']."\t".
        '0'."\t".
        real_ip()."\t".
        $addr['country']."\t".
        'PC'."\t".
        get_user_browser()."\t".
        "退出");
    writelog('cplogs', $errorlog);

    $user->logout();

    $ucdata = empty($user->ucdata)? "" : $user->ucdata;
    //show_message($_LANG['logout'] . $ucdata, array($_LANG['back_up_page'], $_LANG['back_home_lnk']), array($back_act, 'index.php'), 'info');
    header('location:index.php');
}

/* 个人资料页面 */
elseif ($action == 'profile')
{
    include_once(ROOT_PATH . 'includes/lib_transaction.php');
    $user_info = get_profile($user_id);

    $time=strtotime($user_info['birthday'],' 00:00:00');
    $user_info['year'] = date('Y',$time);
    $user_info['month'] = date('m',$time);
    $user_info['day'] = date('d',$time);
    /* 取出注册扩展字段 */
    $sql = 'SELECT * FROM ' . $ecs->table('reg_fields') . ' WHERE type < 2 AND display = 1 ORDER BY dis_order, id';
    $extend_info_list = $db->getAll($sql);

    $sql = 'SELECT reg_field_id, content ' .
           'FROM ' . $ecs->table('reg_extend_info') .
           " WHERE user_id = $user_id";
    $extend_info_arr = $db->getAll($sql);

    $temp_arr = array();
    foreach ($extend_info_arr AS $val)
    {
        $temp_arr[$val['reg_field_id']] = $val['content'];
    }

    foreach ($extend_info_list AS $key => $val)
    {
        switch ($val['id'])
        {
            case 1:     $extend_info_list[$key]['content'] = $user_info['msn']; break;
            case 2:     $extend_info_list[$key]['content'] = $user_info['qq']; break;
            // case 3:     $extend_info_list[$key]['content'] = $user_info['office_phone']; break;
            // case 4:     $extend_info_list[$key]['content'] = $user_info['home_phone']; break;
            case 5:     $extend_info_list[$key]['content'] = $user_info['mobile_phone']; break;
            default:    $extend_info_list[$key]['content'] = empty($temp_arr[$val['id']]) ? '' : $temp_arr[$val['id']] ;
        }
    }
    $smarty->assign('extend_info_list', $extend_info_list);

    /* 密码提示问题 */
    $smarty->assign('passwd_questions', $_LANG['passwd_questions']);
    $head_type = isset($_REQUEST['type']) ? trim($_REQUEST['type']) : '';
    $smarty->assign('profile', $user_info);
    if(!empty($head_type)&&$head_type=="head"){
        //上传浏览图片
        if ($_SERVER['REQUEST_METHOD'] == 'POST'){
        $img_type = isset($_REQUEST['img_type']) ? trim($_REQUEST['img_type']) : '';//获取上传类型

        //********上传预览图片
        if ($img_type =="Preview"){
            if (!is_uploaded_file($_FILES["upfile"][tmp_name]))
            //是否存在文件
            {
                $erro_message="图片不存在!";
                $smarty->assign('message',$erro_message );
                $smarty->display('user_head.dwt');
                 exit;
            }
            //允许上传类型
            $uptypes=array(
            'image/jpg',
            'image/jpeg',
            'image/png',
            'image/pjpeg',
            'image/gif',
            'image/bmp',
            'image/x-png'
            );
            $max_file_size=2000000;     //上传文件大小限制, 单位BYTE
            $destination_folder="head_img/"; //上传文件路径
            $destination_folder_tmp="head_img/tmp/";  //上传文件临时路径
            $file = $_FILES["upfile"]; //获取文件
            if(!in_array($file["type"], $uptypes))
            //检查文件类型
            {
                $erro_message="图片格式不正确!";
                $smarty->assign('message',$erro_message );
                $smarty->display('user_head.dwt');
                 exit;
            }

            if(!file_exists($destination_folder))
            {
                mkdir($destination_folder);
            }
            if(!file_exists($destination_folder_tmp))
            {
                mkdir($destination_folder_tmp);
            }

            $filename=$file["tmp_name"];
            $image_size = getimagesize($filename);
            $pinfo=pathinfo($file["name"]);
            $ftype=$pinfo['extension'];
            $img_name=$user_id."_".time().".".$ftype;
            $destination = $destination_folder.$img_name; //上传图片地址
            $destination_tmp = $destination_folder_tmp.$img_name; // 上传图片临时地址
                if (file_exists($destination) && $overwrite != true)//判断是否有重复
            {
                $erro_message="网络错误!请检测你的网络";
                $smarty->assign('message',$erro_message );
                $smarty->display('user_head.dwt');
                 exit;
            }
            if(!move_uploaded_file($filename,$destination_tmp) || !copy($destination_tmp,$destination) || !FTP()->upload($destination_tmp, $destination))//判断是否移动成功
            {
                $erro_message="网络错误!请检测你的网络";
                $smarty->assign('message',$erro_message );
                $smarty->display('user_head.dwt');
                 exit;
            }
            sleep(1);
            // 分类获取原来图片
            switch ($ftype) {
                case 'jpg':
                    $image = imagecreatefromjpeg($destination);//获取原来的图片
                    break;
                case 'png':
                    $image = imagecreatefrompng($destination);//获取原来的图片
                    break;
                case 'gif':
                    $image = imagecreatefromgif($destination);//获取原来的图片
                    break;
                default:
                    # code...
                    break;
            }
            //判断上传图片是否超出400
            list($width, $height) = getimagesize($destination);
            if($width>400){
            $new_width=400;
            $new_height=(400/$width)*$height;
            $image_p = imagecreatetruecolor($new_width, $new_height);//建立新图片
            imagecopyresampled($image_p, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
            imagejpeg($image_p, $destination, 100);
            imagedestroy($image_p);
            imagedestroy($image);
            }

            $pinfo=pathinfo($destination);
            $fname=$pinfo[basename];
            // 输出预览
            $smarty->assign('preview_url',$destination );
        }
        //上传头像截图
        elseif ($img_type=="Save") {
            $img_x = !empty($_POST['img_x']) ? trim($_POST['img_x']) : '0';//获取截取位置
            $img_y = !empty($_POST['img_y']) ? trim($_POST['img_y']) : '0';
            $img_width = !empty($_POST['img_width']) ? trim($_POST['img_width']) : '120';//截取大小
            $filename = isset($_POST['img_name']) ? trim($_POST['img_name']) : '';//上传图片名称
            // 内容类型
            // header('Content-Type: image/jpeg');
            // 获取新的尺寸
            list($width, $height) = getimagesize($filename);
            $new_width = 120;
            $new_height = 120;
            // 重新取样
            $image_p = imagecreatetruecolor($new_width, $new_height);//建立新图片
            // 获取图片格式
            $pinfo=pathinfo($filename);
            $ftype=$pinfo['extension'];
            switch ($ftype) {
                case 'jpg':
                    $image = imagecreatefromjpeg($filename);//获取原来的图片
                    break;
                case 'png':
                    $image = imagecreatefrompng($filename);//获取原来的图片
                    break;
                case 'gif':
                    $image = imagecreatefromgif($filename);//获取原来的图片
                    break;
                default:
                    # code...
                    break;
            }
            imagecopyresampled($image_p, $image, 0, 0, $img_x, $img_y, $new_width, $new_height, $img_width, $img_width);
            //查询数据库头像图片地址
            $sql= "SELECT head_url FROM ". $ecs->table('user_info') . "WHERE user_id='$user_id'";
            $old_url=$db->getOne($sql);
            if(!empty($old_url)){
                unlink($old_url);//删除原文件
            }

            $unique = $user_id."_".time().".".$ftype;
            $save_url="head_img/head/". $unique;
            $tmp_url ="head_img/tmp/". $unique;
            $sql = "UPDATE " . $ecs->table('user_info') . " SET head_url ='$save_url' WHERE user_id='$user_id'";
            $db->query($sql);
            imagejpeg($image_p, $tmp_url, 100);
            FTP()->upload($tmp_url, $save_url);
            sleep(1);
            imagedestroy($image_p);
            imagedestroy($image);
            $erro_message="修改头像成功";
            $smarty->assign('message',$erro_message );
            $smarty->assign('info',         get_user_default($_SESSION['user_id']));
            unlink($filename);//删除原文件
        }
    }
        $smarty->display('user_head.dwt');
    }
    else{
        $smarty->display('user_transaction.dwt');
    }
}

/* 修改密码 */
elseif ($action == 'profile_pass')
{
    include_once(ROOT_PATH . 'includes/lib_transaction.php');
    $smarty->display('user_transaction.dwt');
}

/* 修改个人资料的处理 */
elseif ($action == 'act_edit_profile')
{
    include_once(ROOT_PATH . 'includes/lib_transaction.php');

    $other['head_url']   = $real_name = isset($_POST['head_url']) ? trim($_POST['head_url']) : '';
    $other['real_name']   = $real_name = isset($_POST['real_name']) ? trim($_POST['real_name']) : '';
    $other['sex']         = $sex = isset($_POST['sex']) ? trim($_POST['sex']) : '';
    $other['birthday']    = $birthday = trim($_POST['birthdayYear']) .'-'. trim($_POST['birthdayMonth']) .'-'. trim($_POST['birthdayDay']);
    $other['email']       = $email = isset($_POST['email']) ? trim($_POST['email']) : '';
    $other['school_name'] = $school_name = isset($_POST['school_name']) ? trim($_POST['school_name']) : '';
    $other['camp']        = $camp = isset($_POST['camp']) ? trim($_POST['camp']) : '';
    $other['studio']      = $studio = isset($_POST['studio']) ? trim($_POST['studio']) : '';
    $other['picture_age'] = $picture_age = isset($_POST['picture_age']) ? trim($_POST['picture_age']) : '';
    $other['qq']          = $qq = isset($_POST['qq']) ? intval($_POST['qq']) : '';
    $other['mobile_phone']= $mobile_phone = isset($_POST['mobile_phone']) ? trim($_POST['mobile_phone']) : '';
    $other['signature']   = $signature = isset($_POST['signature']) ? trim($_POST['signature']) : '';
    $other['hobby']       = $hobby = isset($_POST['hobby']) ? trim($_POST['hobby']) : '';


        //更新个人资料
        $sql = 'UPDATE ' . $ecs->table('user_info') . " SET `real_name`='$real_name', `sex`='$sex', `birthday`='$birthday', `school_name`='$school_name', `camp`='$camp', `studio`='$studio', `picture_age`='$picture_age',  `qq`='$qq', `signature`='$signature', `hobby`='$hobby' WHERE `user_id`='" . $_SESSION['user_id'] . "'";
        $db->query($sql);
        $sql2 = 'UPDATE ' . $ecs->table('users') . " SET `mobile_phone`='$mobile_phone' WHERE `user_id`='" . $_SESSION['user_id'] . "'";
        $db->query($sql2);

    header('location:user.php?act=profile');

}

/* 找回密码-->重置密码界面 */
elseif ($action == 'get_password')
{
        $hash = empty($_GET['hash']) ? '' : trim($_GET['hash']);
        include_once(ROOT_PATH . 'includes/lib_passport.php');
        $data = register_hash('decode', $hash);

        $sql = "SELECT COUNT(*) FROM ".$ecs->table('users')." WHERE user_id = '".$data->user_id."' AND captcha = '".$data->code."'";
        $user = $db->getOne($sql);
        /*判断数据是否为空*/
        if (empty($data->user_name)||empty($data->add_time)||((time()-$data->add_time)>36000)||empty($user)) {
            $smarty->assign('action','reset_fail');
            $smarty->display('email_result.dwt');
        }else{
            $smarty->assign('code',$data->code);
            $smarty->assign('action','reset_password');
            $smarty->display('email_result.dwt');
        }
}



/* 修改会员密码 */
elseif ($action == 'act_edit_password')
{
    include_once(ROOT_PATH . 'includes/lib_passport.php');
    $old_password = isset($_POST['old_password']) ? trim($_POST['old_password']) : null;
    $new_password = isset($_POST['new_password']) ? trim($_POST['new_password']) : '';
    $user_id      = isset($_POST['uid'])  ? intval($_POST['uid']) : $user_id;
    $code         = isset($_POST['code']) ? trim($_POST['code'])  : '';

    if (strlen($new_password) < 6)
    {
        show_message($_LANG['passport_js']['password_shorter']);
    }

    if (($user_info && (!empty($code) && md5($user_info['user_id'] . $_CFG['hash_code'] . $user_info['reg_time']) == $code)) || ($_SESSION['user_id']>0 && $_SESSION['user_id'] == $user_id && $user->check_user($_SESSION['user_name'], $old_password)))
    {

        if ($user->edit_user(array('username'=> (empty($code) ? $_SESSION['user_name'] : $user_info['user_name']), 'old_password'=>$old_password, 'password'=>$new_password), empty($code) ? 0 : 1))
        {
            $sql="UPDATE ".$ecs->table('users'). "SET `ec_salt`='0' WHERE user_id= '".$user_id."'";
            $db->query($sql);
            $user->logout();
            show_message($_LANG['edit_password_success'], $_LANG['relogin_lnk'], 'user.php?act=login', 'info');
        }
        else
        {
            show_message($_LANG['edit_password_failure'], $_LANG['back_page_up'], '', 'info');
        }
    }
    else
    {
        show_message($_LANG['edit_password_failure'], $_LANG['back_page_up'], '', 'info');
    }

}

/* 查看订单列表 */
elseif ($action == 'order_list')
{

    include_once(ROOT_PATH . 'includes/lib_payment.php');
    include_once(ROOT_PATH .'includes/lib_order.php');
    include_once(ROOT_PATH . 'includes/lib_transaction.php');
    $page = isset($_REQUEST['page']) ? intval($_REQUEST['page']) : 1;
    $record_count = $db->getOne("SELECT COUNT(*) FROM " .$ecs->table('order_info'). " WHERE join_id=0 AND user_id = '$user_id'");
    $pager  = get_pager('user.php', array('act' => $action), $record_count, $page ,15);
    $_SESSION['order_count_type'] = $count_type;
    $smarty->assign('order_count_type', $count_type);
    $orders = get_user_orders($user_id, $pager['size'], $pager['start']);
    foreach ($orders as $key => $value) {
        if($value["invoice_no"]){
            $orders[$key]["link"]='<a href="http://q.sto.cn/track.aspx?wen='.$value["invoice_no"].'" target="_blank" >查看物流</a>';
        }
       $orders[$key]["son"]=order_goods($value["order_id"]);
    }
    $merge  = get_user_merge($user_id);
    $count = get_user_count($user_id);

    $smarty->assign('count', $count);
    $smarty->assign('merge',  $merge);
    $smarty->assign('pager',  $pager);
    $smarty->assign('orders', $orders);
// 统计用户订单 alork添加
    $smarty->display('user_transaction.dwt');
}
//售后订单列表
elseif($action =='sale_list'){
    include_once(ROOT_PATH . 'includes/lib_transaction.php');
    $page = isset($_REQUEST['page']) ? intval($_REQUEST['page']) : 1;
    $record_count = $db->getOne("SELECT COUNT(*) FROM " .$ecs->table('sale_service'). " WHERE  user_id = '$user_id'");
    $pager  = get_pager('user.php', array('act' => $action), $record_count, $page ,6);

    $sale_list = get_user_sale($user_id, $pager['size'], $pager['start']);
    $smarty->assign('pager',  $pager);
    $smarty->assign('sale_list', $sale_list);






    $smarty->display('sale_service.dwt');
}
/*售后单详情*/
elseif ($action == 'sale_detail'){

    /* 售后详情 */
        $service_id = !empty($_REQUEST['service_id'])?$_REQUEST['service_id']:"";

        //获取售后表信息
        $sql= "SELECT * FROM ".$GLOBALS['ecs']->table('sale_service') ." WHERE service_id =".$service_id;
        $row = $GLOBALS['db']->getRow($sql);
        $goods_list = array_filter(explode(",",$row['goods']));
        //重组商品数据
        $where="";
        foreach ($goods_list as $key => $value) {
            $rec_id = substr($value,0,strpos($value,"*"));
            $goods_number = substr($value,(strpos($value,"*")+1));
            $goods[$rec_id]=$goods_number;
            $where =" rec_id = ". $rec_id." OR ".$where;
        }
         $where =substr($where,0,-3);
         //获取商品信息
         $sql = " SELECT og.*,g.goods_thumb FROM ".$GLOBALS['ecs']->table('order_goods') ." AS og ".
                " LEFT JOIN ".$GLOBALS['ecs']->table('goods') ." AS g  ON g.goods_id = og.goods_id ".
                " WHERE ".$where;
         $order_goods = $GLOBALS['db']->getAll($sql);
         foreach ($order_goods as $key => $value) {
             foreach ($goods as $keys => $goods_number) {
                 if ($keys == $value['rec_id']) {
                     $order_goods[$key]['goods_number']=$goods_number;
                 }
             }
         }
         //获取操作记录
         $sql = " SELECT * FROM ".$GLOBALS['ecs']->table('handle_record') .
                " WHERE service_id =".$service_id.
                " ORDER BY add_time DESC";
         $handle_record = $GLOBALS['db']->getAll($sql);

         foreach ($handle_record as $key => $value) {
             $handle_record[$key]['add_time']=date("Y-m-d H:i:s",$value['add_time']);
         }
         //如果售后状态为待退货 查询退货单ID
         if($row['handle_state'] == 5){
            $sql = "SELECT return_id FROM ".$GLOBALS['ecs']->table('order_return_info')." WHERE service_id = $service_id";
            $return_id = $db->getOne($sql);
            $smarty->assign('return_id', $return_id);

            //获取订单收货人信息
            $sql = "SELECT address,consignee,mobile FROM ".$GLOBALS['ecs']->table('order_info')." WHERE order_sn = ".$row['order_sn'];
            $consignee = $db->getRow($sql);
            $smarty->assign('consignee', $consignee);

         }
         //重组售后信息
         $row['goods']=$order_goods;
         $row['handle_record']=$handle_record;
         $sale_info = $row;
        $smarty->assign('express_list', $_LANG['ex']);
        $smarty->assign('sale_info', $sale_info);
        $smarty->display('sale_service.dwt');
}
/*AJAX提交退货单*/
elseif ($action == 'order_return'){
    include_once(ROOT_PATH .'includes/cls_json.php');
    $json = new JSON();
    $return_info = !empty($_REQUEST['return_info'])?$_REQUEST['return_info']:'';
    $express_sn = $return_info['express_sn'];//快递单号
    $express_id = $return_info['express_id'];//快递ID
    $address    = $return_info['address'];//退货地址
    $mobile     = $return_info['mobile'];//退货地址
    $consignee  = $return_info['consignee'];//退货地址

    $return_id  = $return_info['return_id'];//退货单ID
    $service_id = $return_info['service_id'];//售后单ID



    $return['error']="1";
    $return['content']="";

    //查询售后状态是否为待退货 不是的话返回错误信息
    $sql = "SELECT * FROM ".$GLOBALS['ecs']->table('sale_service')." WHERE service_id = $service_id";
    $sale_info = $db->getRow($sql);
    if($sale_info['handle_state'] != 5){
        $return['error']="2";
        $return['content']="请勿重复提交";
        die($json->encode($return));
    }



    //修改退货单信息
    $sql =  " UPDATE ".$GLOBALS['ecs']->table('order_return_info').
            " SET express_sn='$express_sn' , express_id ='$express_id' , address = '$address' ,consignee = '$consignee' ,mobile = '$mobile'".
            " WHERE return_id = $return_id ";
    $db->query($sql);

    // 通过处理方式判断后续处理

    switch ($sale_info['handle_type']) {
        case '2':
        //退货退款
    $refund_reason = $_LANG['refund_reason'][$sale_info['service_type']];//退款理由
    //自动生成退款单
    $refund_info = array(
    'order_sn'          => $sale_info['order_sn'],
    'refund_reason'     => $refund_reason,
    'refund_money'      => $sale_info['refund_money'],
    'add_time'          => time(),
    'handle_user'       => $sale_info['consignee'],
    'service_id'        => $sale_info['service_id'],
    'payment_num'       => $sale_info['payment_num'],
    );
    $db->autoExecute($ecs->table('refund'), $refund_info, 'INSERT', '', 'SILENT');
    //修改售后单状态
    $sql =  " UPDATE ".$ecs->table('sale_service').
            " SET handle_state = 6 ".
            " WHERE service_id = $service_id ";
    $db->query($sql);
    //记录操作
    $handle_user = "(买家)".$_SESSION['user_nmae'];
    $content     = "【标题】 买家已退货 <br/>";
    $content     =  $content."【内容】  <br/>";
    $content     =  $content."物流公司： ".$_LANG['ex'][$express_id]." <br/>";
    $content     =  $content."退货单号：  ".$express_sn."<br/>";
    $content     =  $content."退货地址： ".$address." <br/>";
    $content     =  $content."收货人： ".$consignee." <br/>";
    $content     =  $content."收货人电话： ".$mobile." <br/>";

    $handle_record = array(
    'handle_user'       => $handle_user,
    'service_id'        => $service_id,
    'add_time'          => time(),
    'content'           => $content,
    'handle_id'         => 1,
    );
    $db->autoExecute($ecs->table('handle_record'), $handle_record, 'INSERT', '', 'SILENT');
    $return['error']="1";
    $return['content']="提交成功";
    die($json->encode($return));
            break;
        case '3':
        //退货补发
            # code...
            break;
        default:
            # code...
            break;
    }









}
//测试用于清空售后数据
elseif($action == 'delete_sale'){
    $sql = "truncate ".$ecs->table('sale_service');
    $db->query($sql);
    $sql = "truncate ".$ecs->table('order_return_info');
    $db->query($sql);
    $sql = "truncate ".$ecs->table('order_return_goods');
    $db->query($sql);
    $sql = "truncate ".$ecs->table('order_remedy_info');
    $db->query($sql);
    $sql = "truncate ".$ecs->table('order_remedy_goods');
    $db->query($sql);
    $sql = "truncate ".$ecs->table('handle_record');
    $db->query($sql);
    $sql = "truncate ".$ecs->table('refund');
    $db->query($sql);
    $sql = " UPDATE ".$ecs->table('order_goods').
            " set is_sale = 0 ";
    $db->query($sql);
}









/*申请售后*/
elseif ($action == 'sale_service'){
    /* 订单商品 */
    $order_id = isset($_GET['order_id']) ? intval($_GET['order_id']) : 0;

    $sql = "SELECT o.rec_id, o.goods_id,o.is_sale, o.goods_name, o.goods_sku, o.market_price, o.goods_number, g.goods_thumb, g.goods_img, " .
            "o.goods_price, o.goods_attr, o.is_real, o.parent_id, o.is_gift, g.give_integral, " .
            "o.goods_price * o.goods_number AS subtotal, o.extension_code, o.goods_attr_sku " .
            "FROM " . $GLOBALS['ecs']->table('order_goods') . " o ".
            "LEFT JOIN " . $GLOBALS['ecs']->table('goods') . " g ON g.goods_id = o.goods_id " .
            " WHERE o.order_id = '$order_id' AND o.is_sale != 1 AND o.is_gift != 1";
    $goods_list = $db->getAll($sql);
    $smarty->assign('order_id', $order_id);
    foreach ($goods_list as $key => $value) {
        for ($i=1; $i <=  $value['goods_number']; $i++) {
            $goods_list[$key]['goods_number_list'][]=$i;
        }
    }
    $smarty->assign('order_id', $order_id);
    $smarty->assign('goods_list', $goods_list);
    $smarty->display('sale_service.dwt');
}







/*售后表单*/
elseif($action =='sale_service_form' ){
    $order_id = isset($_REQUEST['order_id']) ? intval($_REQUEST['order_id']) : 0;
    $rec_id   = isset($_REQUEST['rec_id']) ? $_REQUEST['rec_id'] : 0;
    $goods_num = isset($_REQUEST['goods_num']) ? $_REQUEST['goods_num'] : 0;
    foreach ($rec_id as $key => $value) {
        $where = " rec_id = ".$value." OR ".$where;
    }
    $where =substr($where,0,-3);



    $sql =  " SELECT o.rec_id,o.goods_name ,o.goods_attr,o.goods_price,o.goods_number,g.goods_thumb ".
            " FROM ".$ecs->table('order_goods')."AS o ".
            " LEFT JOIN ".$ecs->table('goods')." AS g ON g.goods_id =o.goods_id ".
            " WHERE o.is_sale != 1 AND o.is_gift != 1  AND".$where;
    $goods_list = $db->getAll($sql);
    foreach ($goods_list as $key => $value) {
        $goods_list[$key]['goods_number'] = $goods_num[$value['rec_id']];
        $price_count =$value['goods_price']*$goods_num[$value['rec_id']]+$price_count;
    }
    /* 获得用户订单收货地址 */
    $order_info = order_info($order_id);
    //赋值于模板
    $smarty->assign('shop_country',     $_CFG['shop_country']);
    $smarty->assign('shop_province',    get_regions(1, $_CFG['shop_country']));
    $smarty->assign('province_lists',    $province_list);
    $smarty->assign('city_lists',        $city_list);
    $smarty->assign('district_lists',    $district_list);
    $smarty->assign('p_list',    $p_list);
    $smarty->assign('c_list',    $c_list);
    $smarty->assign('d_list',    $d_list);
    $goods="";
    foreach ($goods_list as $key => $value) {
        $goods=$goods.$value['rec_id']."*".$value['goods_number'].",";
    }
    $smarty->assign('goods', $goods);
    $smarty->assign('price_count', round($price_count,2));
    $smarty->assign('order_info', $order_info);
    $smarty->assign('goods_list', $goods_list);
    $smarty->display('sale_service.dwt');
}
/*生成售后单*/
elseif($action =='sale_service_handle' ){
        //接受表单数据
    $goods_list         = !empty($_REQUEST['goods_num'])?$_REQUEST['goods_num']:'';//申请售后的商品及数量
    $service_type       = !empty($_REQUEST['service_type'])?$_REQUEST['service_type']:'';//售后类型
    $question_note      = !empty($_REQUEST['question_note'])?$_REQUEST['question_note']:'';//问题描述
    $pic                = !empty($_REQUEST['pic'])?$_REQUEST['pic']:'';//图片资料
    $consignee          = !empty($_REQUEST['consignee'])?$_REQUEST['consignee']:'';//联系人名称
    $mobile             = !empty($_REQUEST['mobile'])?$_REQUEST['mobile']:'';//电话号码
    $payment_num        = !empty($_REQUEST['payment_num'])?$_REQUEST['payment_num']:'';//支付宝账号
    $add_time           = time();//申请时间
    $order_sn           = !empty($_REQUEST['order_sn'])?$_REQUEST['order_sn']:'';//订单号
    $user_id            = !empty($_SESSION['user_id'])?$_SESSION['user_id']:'';
    $handle_type        = !empty($_REQUEST['handle_type']) ? $_REQUEST['handle_type'] : 0;
    $refund_money       = !empty($_REQUEST['refund_money']) ? $_REQUEST['refund_money'] : 0;
    //售后商品数据处理
    $goods=$goods_list;

    /*判断是否重复提交*/
    //重组商品数据
    $where="";
    $goods_list = array_filter(explode(",",$goods_list));
    foreach ($goods_list as $key => $value) {
        $rec_id = substr($value,0,strpos($value,"*"));
        $goods_number = substr($value,(strpos($value,"*")+1));

        $where ="rec_id = ". $rec_id." OR ".$where;
    }
    $where =substr($where,0,-3);

    $sql =  " SELECT rec_id FROM ".$ecs->table('order_goods').
            " WHERE is_sale = 1 AND (".$where.")";
    $is_sale=$db->getOne($sql);
    if(!empty($is_sale)){
        header("location: user.php?act=error");
        exit();
    }

    //图片处理
    if(!empty($pic)){
        foreach ($pic as $key => $value) {
            // 获取原图尺寸
            list($width, $height) = getimagesize($value);
            $url="sale_pic/".$order_sn."/"; //文件路径
            $file_name=basename($value);//文件名称
            $new_url = $url.$file_name; //上传图片地址
            //检查上传目录是否存在
            if(!file_exists($url))
            {
                //创建目录
                mkdir($url);
            }

            //图片移动处理如果宽大于800进行压缩
            if($width > 800){
                $new_width=800;
                $new_height=round($height*(800/$width));
                $image_p = imagecreatetruecolor($new_width, $new_height);//建立新图片
                        // 获取图片格式
                $pinfo=pathinfo($value);
                $ftype=$pinfo['extension'];
                switch ($ftype) {
                    case 'jpg':
                        $image = imagecreatefromjpeg($value);//获取原来的图片
                        break;
                    case 'png':
                        $image = imagecreatefrompng($value);//获取原来的图片
                        break;
                    case 'gif':
                        $image = imagecreatefromgif($value);//获取原来的图片
                        break;
                    default:
                        # code...
                        break;
                }

                imagecopyresampled($image_p, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);//复制图片
                //将图片输出到文件夹
                switch ($ftype) {
                        case 'jpg':
                            imagejpeg($image_p, $value, 100);
                            break;
                        case 'png':
                            imagepng($image_p, $value, 100);
                            break;
                        case 'gif':
                            imagegif($image_p, $value, 100);
                            break;
                        default:
                            # code...
                            break;
                    }
                //销毁图片
                imagedestroy($image_p);
                imagedestroy($image);
            }

            /* 加载ftp类并创建实例 */
            FTP()->upload(ROOT_PATH . $value, $new_url);
            $pic[$key] = $new_url;
        }
    }

    // 标记商品为已申请售后
    $sql =  " UPDATE ".$ecs->table('order_goods').
            " SET is_sale = 1 ".
            " WHERE ".$where;
    $db->query($sql);

    //整理售后表信息
    $sale_info = array(
    'service_type'      => intval($service_type),
    'pic_1'             => $pic[0],
    'pic_2'             => $pic[1],
    'pic_3'             => $pic[2],
    'consignee'         => $consignee,
    'mobile'            => $mobile,
    'add_time'          => $add_time,
    'order_sn'          => $order_sn,
    'user_id'           => $user_id,
    'goods'             => $goods,
    'handle_type'       => $handle_type,
    'refund_money'      => $refund_money,
    'payment_num'       => $payment_num,
    );
        /* 把售后单信息写入sale_service表 */
    $GLOBALS['db']->autoExecute($GLOBALS['ecs']->table('sale_service'), $sale_info, 'INSERT', '', 'SILENT');
    $service_id=$db->insert_id();

    /*系统化语言*/
    $content = "买家于".date("Y-m-d h:i:s",time())."申请了售后<br/>";

    $content = $content."售后类型:".$_LANG['sale_question'][$service_type]."<br/>";
    $content = $content."处理方式:".$_LANG['handle_type'][$handle_type]."<br/>";
    $content = $content."退款金额为:".$refund_money."元<br/>";
    if(!empty($question_note)){
        $content = $content."问题描述:".$question_note."<br/>";
    }
    $handle_user = "(买家)".$_SESSION['user_name'];

    /*将操作记录*/
    $handle_record = array(
    'handle_user'       => $handle_user,
    'service_id'        => $service_id,
    'add_time'          => time(),
    'content'           => $content,
    'handle_id'         => 1,
    );
    $GLOBALS['db']->autoExecute($GLOBALS['ecs']->table('handle_record'), $handle_record, 'INSERT', '', 'SILENT');




    header("location: user.php?act=done");
    exit();
}
/*完成售后单提示*/
elseif ($action == 'done'||$action == 'error')
{



    $smarty->display('sale_service.dwt');
}



/* 查看订单详情 */
elseif ($action == 'order_detail')
{
    include_once(ROOT_PATH . 'includes/lib_transaction.php');
    include_once(ROOT_PATH . 'includes/lib_payment.php');
    include_once(ROOT_PATH . 'includes/lib_order.php');
    include_once(ROOT_PATH . 'includes/lib_clips.php');

    $order_id = isset($_GET['order_id']) ? intval($_GET['order_id']) : 0;

    /* 订单详情 */
    $order = get_order_detail($order_id, $user_id);

    if ($order === false)
    {
        $err->show($_LANG['back_home_lnk'], './');

        exit;
    }

    /* 是否显示添加到购物车 */
    if ($order['extension_code'] != 'group_buy' && $order['extension_code'] != 'exchange_goods')
    {
        $smarty->assign('allow_to_cart', 1);
    }

    /* 订单商品 */
    $goods_list = order_goods($order_id);
    foreach ($goods_list AS $key => $value)
    {
        $goods_list[$key]['market_price'] = price_format($value['market_price'], false);
        $goods_list[$key]['goods_price']  = price_format($value['goods_price'], false);
        $goods_list[$key]['subtotal']     = price_format($value['subtotal'], false);
        if($value['extension_code']=='libao'){
            if($value['parent_id'] && $value['goods_id'] == 0){
                $libaoInfo[$value['parent_id']] = $value;
            }else{
                $libaoGoods[$value['parent_id']][] = $value;
                unset($goods_list[$key]);
            }
        }
    }


    /* 未发货，未付款时允许更换支付方式 */
    if ($order['order_amount'] > 0 && $order['pay_status'] == PS_UNPAYED && $order['order_status'] == OS_UNCONFIRMED && $order['shipping_status'] == SS_UNSHIPPED)
    {
        $payment_list = available_payment_list(1, 0, false);

        /* 过滤掉当前支付方式和余额支付方式 */
        if(is_array($payment_list))
        {
            foreach ($payment_list as $key => $payment)
            {
                if ($payment['pay_id'] == $order['pay_id'] || $payment['pay_code'] == 'balance')
                {
                    unset($payment_list[$key]);
                }
                if($payment['pay_id'] == 3 && $order['surplus'] > 0){
                    unset($payment_list[$key]);
                }
            }
        }
        $smarty->assign('payment_list', $payment_list);

    }

    /* 订单 支付 配送 状态语言项 */
    $order['order_status_name'] = $_LANG['os'][$order['order_status']];
    $order['pay_status_name'] = $_LANG['ps'][$order['pay_status']];
    $order['shipping_status_name'] = $_LANG['ss'][$order['shipping_status']];
    $province = $order['province']?selectaddress($order['province'])." ":'';
    $city = $order['city']?selectaddress($order['city'])." ":'';
    $district = $order['district']?selectaddress($order['district'])." ":'';
    $address = $order['address'];
    $order['addr'] = $province . $city . $district;
    $smarty->assign('order',      $order);
    $smarty->assign('goods_list', $goods_list);
    $smarty->display('user_transaction.dwt');
}


/* 取消订单 */
elseif ($action == 'cancel_order')
{
    include_once(ROOT_PATH . 'includes/lib_transaction.php');
    include_once(ROOT_PATH . 'includes/lib_order.php');

    $order_id = isset($_GET['order_id']) ? intval($_GET['order_id']) : 0;
    $order=order_info($order_id);

    $area_id=is_buy($order);
    $goods_list=order_goods($order_id);
    if (cancel_order($order_id, $user_id))
    {
        ecs_header("Location: user.php?act=order_list\n");
        exit;
    }
    else
    {
        $err->show($_LANG['order_list_lnk'], 'user.php?act=order_list');
    }

}


/* 收货地址列表界面*/
elseif ($action == 'address_list')
{
    include_once(ROOT_PATH . 'includes/lib_transaction.php');
    include_once(ROOT_PATH . 'languages/' .$_CFG['lang']. '/shopping_flow.php');
    $smarty->assign('lang',  $_LANG);

    // 获取地区选择
    assign_area();

    /* 取得国家列表、商店所在国家、商店所在国家的省列表 */
    $smarty->assign('country_list',       get_regions());
    $smarty->assign('shop_province_list', get_regions(1, $_CFG['shop_country']));

    /* 获得用户所有的收货人信息 */
    $consignee_list = get_consignee_list($_SESSION['user_id']);
    $count=count($consignee_list);
    $smarty->assign('consignee_list', $consignee_list);

    //取得国家列表，如果有收货人列表，取得省市区列表
    foreach ($consignee_list AS $region_id => $consignee)
    {
        $consignee['country']  = isset($consignee['country'])  ? intval($consignee['country'])  : 0;
        $consignee['province'] = isset($consignee['province']) ? intval($consignee['province']) : 0;
        $consignee['city']     = isset($consignee['city'])     ? intval($consignee['city'])     : 0;

        $province_list[$region_id] = get_regions(1, $consignee['country']);
        $city_list[$region_id]     = get_regions(2, $consignee['province']);
        $district_list[$region_id] = get_regions(3, $consignee['city']);
        $p_list[$region_id] = selectaddress($consignee['province']);
        $c_list[$region_id] = selectaddress($consignee['city']);
        $d_list[$region_id] = selectaddress($consignee['district']);
    }
    /* 获取默认收货ID */
    $address_id  = $db->getOne("SELECT address_id FROM " .$ecs->table('users'). " WHERE user_id='$user_id'");
    //赋值于模板
    $smarty->assign('real_goods_count', 1);
    $smarty->assign('shop_country',     $_CFG['shop_country']);
    $smarty->assign('shop_province',    get_regions(1, $_CFG['shop_country']));
    $smarty->assign('province_lists',    $province_list);
    $smarty->assign('city_lists',        $city_list);
    $smarty->assign('district_lists',    $district_list);
    $smarty->assign('p_list',    $p_list);
    $smarty->assign('c_list',    $c_list);
    $smarty->assign('d_list',    $d_list);
    $smarty->assign('count',    $count);
    $smarty->assign('address',          $address_id);
    $smarty->assign('currency_format',  $_CFG['currency_format']);
    $smarty->assign('integral_scale',   $_CFG['integral_scale']);
    $smarty->assign('name_of_region',   array($_CFG['name_of_region_1'], $_CFG['name_of_region_2'], $_CFG['name_of_region_3'], $_CFG['name_of_region_4']));
    $smarty->display('user_transaction.dwt');
}

/* 添加/编辑收货地址的处理 */
elseif ($action == 'act_edit_address')
{
    include_once(ROOT_PATH . 'includes/lib_transaction.php');
    include_once(ROOT_PATH . 'languages/' .$_CFG['lang']. '/shopping_flow.php');
    $smarty->assign('lang', $_LANG);
    $count =  count(get_consignee_list($_SESSION['user_id']));

    $district = isset($_POST['district'])  ? intval($_POST['district']) : header("location:user.php?act=address_list");
    $set_consignee = set_consignee($district,'',true);
    $address = array(
        'num'        => $count,
        'user_id'    => $user_id,
        'address_id' => intval($_POST['address_id']),
        'country'    => isset($set_consignee['country'])   ? intval($set_consignee['country'])  : 0,
        'province'   => isset($set_consignee['province'])  ? intval($set_consignee['province']) : 0,
        'city'       => isset($set_consignee['city'])      ? intval($set_consignee['city'])     : 0,
        'district'   => isset($set_consignee['district'])  ? intval($set_consignee['district']) : 0,
        'address'    => isset($_POST['address'])   ? compile_str(trim($_POST['address']))    : '',
        'consignee'  => isset($_POST['consignee']) ? compile_str(trim($_POST['consignee']))  : '',
        'email'      => isset($_POST['email'])     ? compile_str(trim($_POST['email']))      : '',
        'mobile'     => isset($_POST['mobile'])    ? compile_str(make_semiangle(trim($_POST['mobile']))) : '',
        );

    if(strlen($address['mobile']) != 11){
        show_message('手机号码出错，请重新输入！');
        exit;
    }
    if (update_address($address))
    {
        header("location:user.php?act=address_list");
    }
}

/* 删除收货地址 */
elseif ($action == 'drop_consignee')
{
    include_once('includes/lib_transaction.php');

    $consignee_id = intval($_GET['id']);

    if (drop_consignee($consignee_id))
    {
        ecs_header("Location: user.php?act=address_list\n");
        exit;
    }
    else
    {
        show_message($_LANG['del_address_false']);
    }
}

/* 显示收藏商品列表 */
elseif ($action == 'collection_list')
{
    include_once(ROOT_PATH . 'includes/lib_clips.php');

    $page = isset($_REQUEST['page']) ? intval($_REQUEST['page']) : 1;

    $record_count = $db->getOne("SELECT COUNT(*) FROM " .$ecs->table('collect_goods').
                                " WHERE user_id='$user_id' ORDER BY add_time DESC");

    $pager = get_pager('user.php', array('act' => $action), $record_count, $page);
    $smarty->assign('pager', $pager);
    $smarty->assign('goods_list', get_collection_goods($user_id, $pager['size'], $pager['start']));
    $smarty->assign('url',        $ecs->url());
    $lang_list = array(
        'UTF8'   => $_LANG['charset']['utf8'],
        'GB2312' => $_LANG['charset']['zh_cn'],
        'BIG5'   => $_LANG['charset']['zh_tw'],
    );

    $smarty->assign('lang_list',  $lang_list);
    $smarty->assign('user_id',  $user_id);
    $smarty->display('user_clips.dwt');
}

/* 删除收藏的商品 */
elseif ($action == 'delete_collection')
{
    include_once(ROOT_PATH . 'includes/lib_clips.php');

    $collection_id = isset($_GET['collection_id']) ? intval($_GET['collection_id']) : 0;

    if ($collection_id > 0)
    {
        $db->query('DELETE FROM ' .$ecs->table('collect_goods'). " WHERE rec_id='$collection_id' AND user_id ='$user_id'" );
    }

    ecs_header("Location: user.php?act=collection_list\n");
    exit;
}
/* AJAX删除收藏的商品 */
elseif ($action == 'delcollect')
{
    include_once(ROOT_PATH . 'includes/lib_clips.php');

    $id = isset($_GET['id']) ? intval($_GET['id']) : 0;

    if ($id > 0)
    {
        $db->query('DELETE FROM ' .$ecs->table('collect_goods'). " WHERE goods_id='$id' AND user_id ='$user_id'" );
    }
    include_once(ROOT_PATH .'includes/cls_json.php');
    $json = new JSON();
    die($json->encode(1));
}


/* 删除看过的商品 */
elseif ($action == 'dellookat')
{
    include_once(ROOT_PATH . 'includes/lib_clips.php');

    $id = isset($_GET['id']) ? intval($_GET['id']) : 0;

    if ($id > 0)
    {
        $db->query('DELETE FROM ' .$ecs->table('user_lookat'). " WHERE goods_id='$id' AND user_id ='$user_id'" );
    }
    include_once(ROOT_PATH .'includes/cls_json.php');
    $json = new JSON();
    die($json->encode(1));
}

/* 添加关注商品 */
elseif ($action == 'add_to_attention')
{
    $rec_id = (int)$_GET['rec_id'];
    if ($rec_id)
    {
        $db->query('UPDATE ' .$ecs->table('collect_goods'). "SET is_attention = 1 WHERE rec_id='$rec_id' AND user_id ='$user_id'" );
    }
    ecs_header("Location: user.php?act=collection_list\n");
    exit;
}
/* 取消关注商品 */
elseif ($action == 'del_attention')
{
    $rec_id = (int)$_GET['rec_id'];
    if ($rec_id)
    {
        $db->query('UPDATE ' .$ecs->table('collect_goods'). "SET is_attention = 0 WHERE rec_id='$rec_id' AND user_id ='$user_id'" );
    }
    ecs_header("Location: user.php?act=collection_list\n");
    exit;
}
/* 显示留言列表 */
// elseif ($action == 'message_list')
// {
//     include_once(ROOT_PATH . 'includes/lib_clips.php');

//     $page = isset($_REQUEST['page']) ? intval($_REQUEST['page']) : 1;

//     $order_id = empty($_GET['order_id']) ? 0 : intval($_GET['order_id']);
//     $order_info = array();

//     /* 获取用户留言的数量 */
//     if ($order_id)
//     {
//         $sql = "SELECT COUNT(*) FROM " .$ecs->table('feedback').
//                 " WHERE parent_id = 0 AND order_id = '$order_id' AND user_id = '$user_id'";
//         $order_info = $db->getRow("SELECT * FROM " . $ecs->table('order_info') . " WHERE order_id = '$order_id' AND user_id = '$user_id'");
//         $order_info['url'] = 'user.php?act=order_detail&order_id=' . $order_id;
//     }
//     else
//     {
//         $sql = "SELECT COUNT(*) FROM " .$ecs->table('feedback').
//            " WHERE parent_id = 0 AND user_id = '$user_id' AND user_name = '" . $_SESSION['user_name'] . "' AND order_id=0";
//     }

//     $record_count = $db->getOne($sql);
//     $act = array('act' => $action);

//     if ($order_id != '')
//     {
//         $act['order_id'] = $order_id;
//     }

//     $pager = get_pager('user.php', $act, $record_count, $page, 5);

//     $smarty->assign('message_list', get_message_list($user_id, $_SESSION['user_name'], $pager['size'], $pager['start'], $order_id));
//     $smarty->assign('pager',        $pager);
//     $smarty->assign('order_info',   $order_info);
//     $smarty->display('user_clips.dwt');
// }
/* 显示评论列表 */
elseif ($action == 'comment_list')
{
    include_once(ROOT_PATH . 'includes/lib_clips.php');

    $page = isset($_REQUEST['page']) ? intval($_REQUEST['page']) : 1;

    /* 获取用户留言的数量 */
    $sql = "SELECT COUNT(*) FROM " .$ecs->table('comment').
           " WHERE parent_id = 0 AND user_id = '$user_id'";
    $record_count = $db->getOne($sql);
    $pager = get_pager('user.php', array('act' => $action), $record_count, $page, 5);

    $smarty->assign('comment_list', get_comment_list($user_id, $pager['size'], $pager['start']));
    $smarty->assign('pager',        $pager);
    $smarty->display('user_clips.dwt');
}

/* 显示奖励列表 */
elseif ($action == 'reward_list')
{
    include_once(ROOT_PATH . 'includes/lib_clips.php');

    $page = isset($_REQUEST['page']) ? intval($_REQUEST['page']) : 1;

    /* 获取用户留言的数量 */
    $sql = "SELECT COUNT(*) FROM " .$ecs->table('comment').
    " WHERE parent_id = 0 AND user_id = '$user_id'";
    $record_count = $db->getOne($sql);
    $pager = get_pager('user.php', array('act' => $action), $record_count, $page, 5);

    $smarty->assign('comment_list', get_comment_list($user_id, $pager['size'], $pager['start']));
    $smarty->assign('pager',        $pager);
    $smarty->display('user_clips.dwt');
}

// 添加订单留言
elseif ($action == 'act_add_message')
{
    include_once(ROOT_PATH . 'includes/lib_clips.php');
        $order = array(
            'postscript' => isset($_POST['msg_content']) ? trim($_POST['msg_content']) : '',
        );
        $msg_content = isset($_POST['msg_content']) ? trim($_POST['msg_content']) : '';
        $order_id = empty($_POST['order_id']) ? 0 : intval($_POST['order_id']);
        $acts = isset($_POST['acts']) ? trim($_POST['acts']) : '';
        $db->autoExecute($GLOBALS['ecs']->table('order_info'), $order, 'UPDATE' , "order_id = $order_id");
        header("location:user.php?act=$acts&order_id=$order_id;");
}





/* 添加我的留言 */
// elseif ($action == 'act_add_message')
// {
//     include_once(ROOT_PATH . 'includes/lib_clips.php');

//     $message = array(
//         'user_id'     => $user_id,
//         'user_name'   => $_SESSION['user_name'],
//         'user_email'  => $_SESSION['email'],
//         'msg_type'    => isset($_POST['msg_type']) ? intval($_POST['msg_type'])     : 0,
//         'msg_title'   => isset($_POST['msg_title']) ? trim($_POST['msg_title'])     : '',
//         'msg_content' => isset($_POST['msg_content']) ? trim($_POST['msg_content']) : '',
//         'order_id'=>empty($_POST['order_id']) ? 0 : intval($_POST['order_id']),
//         'upload'      => (isset($_FILES['message_img']['error']) && $_FILES['message_img']['error'] == 0) || (!isset($_FILES['message_img']['error']) && isset($_FILES['message_img']['tmp_name']) && $_FILES['message_img']['tmp_name'] != 'none')
//          ? $_FILES['message_img'] : array()
//      );

//     if (add_message($message))
//     {
//         show_message($_LANG['add_message_success'], $_LANG['message_list_lnk'], 'user.php?act=message_list&order_id=' . $message['order_id'],'info');
//     }
//     else
//     {
//         $err->show($_LANG['message_list_lnk'], 'user.php?act=message_list');
//     }
// }

/* 标签云列表 */
elseif ($action == 'tag_list')
{
    include_once(ROOT_PATH . 'includes/lib_clips.php');

    $good_id = isset($_GET['id']) ? intval($_GET['id']) : 0;

    $smarty->assign('tags',      get_user_tags($user_id));
    $smarty->assign('tags_from', 'user');
    $smarty->display('user_clips.dwt');
}

/* 删除标签云的处理 */
elseif ($action == 'act_del_tag')
{
    include_once(ROOT_PATH . 'includes/lib_clips.php');

    $tag_words = isset($_GET['tag_words']) ? trim($_GET['tag_words']) : '';
    delete_tag($tag_words, $user_id);

    ecs_header("Location: user.php?act=tag_list\n");
    exit;

}

/* 确认收货 */
elseif ($action == 'affirm_received')
{
    include_once(ROOT_PATH . 'includes/lib_transaction.php');

    $order_id = isset($_GET['order_id']) ? intval($_GET['order_id']) : 0;
    include_once('includes/cls_json.php');
    $json = new JSON;

    $sql = "SELECT * FROM ".$GLOBALS['ecs']->table('users') ." WHERE user_id = '$user_id'";
    $users = $GLOBALS['db']->GetRow($sql);
    $username = $users['user_name'];
    $password = $_REQUEST['password'];
    if ($user->login($username, $password, 1))
    {
        if (affirm_received($order_id, $user_id))
        {
            $result['error']   = 0;
            die($json->encode($result));
        }
        else
        {
            $result['error']   = 1;
            $result['content'] = '订单出错，请联系客服！';
            die($json->encode($result));
        }
    }
    else
    {
        $result['error']   = 1;
        $result['content'] = '密码错误！';
        die($json->encode($result));
    }

}


/* 会员退款申请界面 */
elseif ($action == 'account_raply')
{
    $smarty->display('user_transaction.dwt');
}

/* 会员预付款界面 */
elseif ($action == 'account_deposit')
{
    include_once(ROOT_PATH . 'includes/lib_clips.php');

    $surplus_id = isset($_GET['id']) ? intval($_GET['id']) : 0;
    $account    = get_surplus_info($surplus_id);

    $smarty->assign('payment', get_online_payment_list(false));
    $smarty->assign('order',   $account);
    $smarty->display('user_transaction.dwt');
}

/* 会员账目明细界面 */
elseif ($action == 'account_detail')
{
    include_once(ROOT_PATH . 'includes/lib_clips.php');

    $page = isset($_REQUEST['page']) ? intval($_REQUEST['page']) : 1;

    $account_type = 'user_money';

    /* 获取记录条数 */
    $sql = "SELECT COUNT(*) FROM " .$ecs->table('account_log').
           " WHERE user_id = '$user_id'" .
           " AND $account_type <> 0 ";
    $record_count = $db->getOne($sql);

    //分页函数
    $pager = get_pager('user.php', array('act' => $action), $record_count, $page);

    //获取剩余余额
    $surplus_amount = get_user_surplus($user_id);
    if (empty($surplus_amount))
    {
        $surplus_amount = 0;
    }

    //获取余额记录
    $account_log = array();
    $sql = "SELECT * FROM " . $ecs->table('account_log') .
           " WHERE user_id = '$user_id'" .
           " AND $account_type <> 0 " .
           " ORDER BY log_id DESC";
    $res = $GLOBALS['db']->selectLimit($sql, $pager['size'], $pager['start']);

    while ($row = $db->fetchRow($res))
    {
        $row['change_time'] = local_date($_CFG['date_format'], $row['change_time']);
        $row['type'] = $row[$account_type] > 0 ?  "+" : "" ;
        //$row['user_money'] = price_format(abs($row['user_money']), false);
        $row['frozen_money'] = price_format(abs($row['frozen_money']), false);
        $row['rank_points'] = abs($row['rank_points']);
        $row['pay_points'] = abs($row['pay_points']);
        $row['short_change_desc'] = sub_str($row['change_desc'], 60);
        $row['amount'] = $row['type'].$row[$account_type];
        $account_log[] = $row;
    }

    //模板赋值
    $smarty->assign('surplus_amount', price_format($surplus_amount, false));
    $smarty->assign('account_log',    $account_log);
    $smarty->assign('pager',          $pager);
    $smarty->display('user_transaction.dwt');
}

/* 对会员余额申请的处理 */
elseif ($action == 'act_account')
{
    include_once(ROOT_PATH . 'includes/lib_clips.php');
    include_once(ROOT_PATH . 'includes/lib_order.php');
    $amount = isset($_POST['amount']) ? floatval($_POST['amount']) : 0;
    if ($amount <= 0)
    {
        show_message($_LANG['amount_gt_zero']);
    }

    /* 变量初始化 */
    $surplus = array(
            'user_id'      => $user_id,
            'rec_id'       => !empty($_POST['rec_id'])      ? intval($_POST['rec_id'])       : 0,
            'process_type' => isset($_POST['surplus_type']) ? intval($_POST['surplus_type']) : 0,
            'payment_id'   => isset($_POST['payment_id'])   ? intval($_POST['payment_id'])   : 0,
            'user_note'    => isset($_POST['user_note'])    ? trim($_POST['user_note'])      : '',
            'amount'       => $amount
    );

    /* 退款申请的处理 */
    if ($surplus['process_type'] == 1)
    {
        /* 判断是否有足够的余额的进行退款的操作 */
        $sur_amount = get_user_surplus($user_id);
        if ($amount > $sur_amount)
        {
            $content = $_LANG['surplus_amount_error'];
            show_message($content, $_LANG['back_page_up'], '', 'info');
        }

        //插入会员账目明细
        $amount = '-'.$amount;
        $surplus['payment'] = '';
        $surplus['rec_id']  = insert_user_account($surplus, $amount);

        /* 如果成功提交 */
        if ($surplus['rec_id'] > 0)
        {
            $content = $_LANG['surplus_appl_submit'];
            show_message($content, $_LANG['back_account_log'], 'user.php?act=account_log', 'info');
        }
        else
        {
            $content = $_LANG['process_false'];
            show_message($content, $_LANG['back_page_up'], '', 'info');
        }
    }
    /* 如果是会员预付款，跳转到下一步，进行线上支付的操作 */
    else
    {
        if ($surplus['payment_id'] <= 0)
        {
            show_message($_LANG['select_payment_pls']);
        }

        include_once(ROOT_PATH .'includes/lib_payment.php');

        //获取支付方式名称
        $payment_info = array();
        $payment_info = payment_info($surplus['payment_id']);
        $surplus['payment'] = $payment_info['pay_name'];

        if ($surplus['rec_id'] > 0)
        {
            //更新会员账目明细
            $surplus['rec_id'] = update_user_account($surplus);
        }
        else
        {
            //插入会员账目明细
            $surplus['rec_id'] = insert_user_account($surplus, $amount);
        }

        //取得支付信息，生成支付代码
        $payment = unserialize_config($payment_info['pay_config']);

        //生成伪订单号, 不足的时候补0
        $order = array();
        $order['order_sn']       = $surplus['rec_id'];
        $order['user_name']      = $_SESSION['user_name'];
        $order['surplus_amount'] = $amount;

        //计算支付手续费用
        $payment_info['pay_fee'] = pay_fee($surplus['payment_id'], $order['surplus_amount'], 0);

        //计算此次预付款需要支付的总金额
        $order['order_amount']   = $amount + $payment_info['pay_fee'];

        //记录支付log
        $order['log_id'] = insert_pay_log($surplus['rec_id'], $order['order_amount'], $type=PAY_SURPLUS, 0);

        /* 调用相应的支付方式文件 */
        include_once(ROOT_PATH . 'includes/modules/payment/' . $payment_info['pay_code'] . '.php');

        /* 取得在线支付方式的支付按钮 */
        $pay_obj = new $payment_info['pay_code'];
        $payment_info['pay_button'] = $pay_obj->get_code($order, $payment);

        /* 模板赋值 */
        $smarty->assign('payment', $payment_info);
        $smarty->assign('pay_fee', price_format($payment_info['pay_fee'], false));
        $smarty->assign('amount',  price_format($amount, false));
        $smarty->assign('order',   $order);
        $smarty->display('user_transaction.dwt');
    }
}

/* 删除会员余额 */
elseif ($action == 'cancel')
{
    include_once(ROOT_PATH . 'includes/lib_clips.php');

    $id = isset($_GET['id']) ? intval($_GET['id']) : 0;
    if ($id == 0 || $user_id == 0)
    {
        ecs_header("Location: user.php?act=account_log\n");
        exit;
    }

    $result = del_user_account($id, $user_id);
    if ($result)
    {
        ecs_header("Location: user.php?act=account_log\n");
        exit;
    }
}

/* 会员通过帐目明细列表进行再付款的操作 */
elseif ($action == 'pay')
{
    include_once(ROOT_PATH . 'includes/lib_clips.php');
    include_once(ROOT_PATH . 'includes/lib_payment.php');
    include_once(ROOT_PATH . 'includes/lib_order.php');

    //变量初始化
    $surplus_id = isset($_GET['id'])  ? intval($_GET['id'])  : 0;
    $payment_id = isset($_GET['pid']) ? intval($_GET['pid']) : 0;

    if ($surplus_id == 0)
    {
        ecs_header("Location: user.php?act=account_log\n");
        exit;
    }

    //如果原来的支付方式已禁用或者已删除, 重新选择支付方式
    if ($payment_id == 0)
    {
        ecs_header("Location: user.php?act=account_deposit&id=".$surplus_id."\n");
        exit;
    }

    //获取单条会员帐目信息
    $order = array();
    $order = get_surplus_info($surplus_id);

    //支付方式的信息
    $payment_info = array();
    $payment_info = payment_info($payment_id);

    /* 如果当前支付方式没有被禁用，进行支付的操作 */
    if (!empty($payment_info))
    {
        //取得支付信息，生成支付代码
        $payment = unserialize_config($payment_info['pay_config']);

        //生成伪订单号
        $order['order_sn'] = $surplus_id;

        //获取需要支付的log_id
        $order['log_id'] = get_paylog_id($surplus_id, $pay_type = PAY_SURPLUS);

        $order['user_name']      = $_SESSION['user_name'];
        $order['surplus_amount'] = $order['amount'];

        //计算支付手续费用
        $payment_info['pay_fee'] = pay_fee($payment_id, $order['surplus_amount'], 0);

        //计算此次预付款需要支付的总金额
        $order['order_amount']   = $order['surplus_amount'] + $payment_info['pay_fee'];

        //如果支付费用改变了，也要相应的更改pay_log表的order_amount
        $order_amount = $db->getOne("SELECT order_amount FROM " .$ecs->table('pay_log')." WHERE log_id = '$order[log_id]'");
        if ($order_amount <> $order['order_amount'])
        {
            $db->query("UPDATE " .$ecs->table('pay_log').
                       " SET order_amount = '$order[order_amount]' WHERE log_id = '$order[log_id]'");
        }

        /* 调用相应的支付方式文件 */
        include_once(ROOT_PATH . 'includes/modules/payment/' . $payment_info['pay_code'] . '.php');

        /* 取得在线支付方式的支付按钮 */
        $pay_obj = new $payment_info['pay_code'];
        $payment_info['pay_button'] = $pay_obj->get_code($order, $payment);

        /* 模板赋值 */
        $smarty->assign('payment', $payment_info);
        $smarty->assign('order',   $order);
        $smarty->assign('pay_fee', price_format($payment_info['pay_fee'], false));
        $smarty->assign('amount',  price_format($order['surplus_amount'], false));
        $smarty->assign('action',  'act_account');
        $smarty->display('user_transaction.dwt');
    }
    /* 重新选择支付方式 */
    else
    {
        include_once(ROOT_PATH . 'includes/lib_clips.php');

        $smarty->assign('payment', get_online_payment_list());
        $smarty->assign('order',   $order);
        $smarty->assign('action',  'account_deposit');
        $smarty->display('user_transaction.dwt');
    }
}

/* 添加标签(ajax) */
elseif ($action == 'add_tag')
{
    include_once('includes/cls_json.php');
    include_once('includes/lib_clips.php');

    $result = array('error' => 0, 'message' => '', 'content' => '');
    $id     = isset($_POST['id']) ? intval($_POST['id']) : 0;
    $tag    = isset($_POST['tag']) ? json_str_iconv(trim($_POST['tag'])) : '';

    if ($user_id == 0)
    {
        /* 用户没有登录 */
        $result['error']   = 1;
        $result['message'] = $_LANG['tag_anonymous'];
    }
    else
    {
        add_tag($id, $tag); // 添加tag
        clear_cache_files('goods'); // 删除缓存

        /* 重新获得该商品的所有缓存 */
        $arr = get_tags($id);

        foreach ($arr AS $row)
        {
            $result['content'][] = array('word' => htmlspecialchars($row['tag_words']), 'count' => $row['tag_count']);
        }
    }

    $json = new JSON;

    echo $json->encode($result);
    exit;
}

/* 添加收藏商品(ajax) */
elseif ($action == 'collect')
{
    include_once(ROOT_PATH .'includes/cls_json.php');
    $json = new JSON();
    $result = array('error' => 0, 'message' => '');
    $goods_id = $_GET['id'];

    if (!isset($_SESSION['user_id']) || $_SESSION['user_id'] == 0)
    {
        $result['error'] = 1;
        $result['message'] = $_LANG['login_please'];
        die($json->encode($result));
    }
    else
    {
        /* 检查是否已经存在于用户的收藏夹 */
        $sql = "SELECT COUNT(*) FROM " .$GLOBALS['ecs']->table('collect_goods') .
            " WHERE user_id='$_SESSION[user_id]' AND goods_id = '$goods_id'";
        if ($GLOBALS['db']->GetOne($sql) > 0)
        {
            $result['error'] = 1;
            $result['message'] = $GLOBALS['_LANG']['collect_existed'];
            die($json->encode($result));
        }
        else
        {
            $time = gmtime();
            $sql = "INSERT INTO " .$GLOBALS['ecs']->table('collect_goods'). " (user_id, goods_id, add_time)" .
                    "VALUES ('$_SESSION[user_id]', '$goods_id', '$time')";

            if ($GLOBALS['db']->query($sql) === false)
            {
                $result['error'] = 1;
                $result['message'] = $GLOBALS['db']->errorMsg();
                die($json->encode($result));
            }
            else
            {
                $result['error'] = 0;
                $result['message'] = $GLOBALS['_LANG']['collect_success'];
                die($json->encode($result));
            }
        }
    }
}

/* 删除留言 */
elseif ($action == 'del_msg')
{
    $id = isset($_GET['id']) ? intval($_GET['id']) : 0;
    $order_id = empty($_GET['order_id']) ? 0 : intval($_GET['order_id']);

    if ($id > 0)
    {
        $sql = 'SELECT user_id, message_img FROM ' .$ecs->table('feedback'). " WHERE msg_id = '$id' LIMIT 1";
        $row = $db->getRow($sql);
        if ($row && $row['user_id'] == $user_id)
        {
            /* 验证通过，删除留言，回复，及相应文件 */
            if ($row['message_img'])
            {
                @unlink(ROOT_PATH . DATA_DIR . '/feedbackimg/'. $row['message_img']);
            }
            $sql = "DELETE FROM " .$ecs->table('feedback'). " WHERE msg_id = '$id' OR parent_id = '$id'";
            $db->query($sql);
        }
    }
    ecs_header("Location: user.php?act=message_list&order_id=$order_id\n");
    exit;
}

/* 删除评论 */
elseif ($action == 'del_cmt')
{
    $id = isset($_GET['id']) ? intval($_GET['id']) : 0;
    if ($id > 0)
    {
        $sql = "DELETE FROM " .$ecs->table('comment'). " WHERE comment_id = '$id' AND user_id = '$user_id'";
        $db->query($sql);
    }
    ecs_header("Location: user.php?act=comment_list\n");
    exit;
}

/* 将指定订单中商品添加到购物车 */
elseif ($action == 'return_to_cart')
{
    include_once(ROOT_PATH .'includes/cls_json.php');
    include_once(ROOT_PATH .'includes/lib_transaction.php');
    $json = new JSON();
    $result = array('error' => 0, 'message' => '', 'content' => '');
    $order_id = isset($_REQUEST['order_id']) ? intval($_REQUEST['order_id']) : 0;
    if ($order_id == 0)
    {
        $result['error']   = 1;
        $result['message'] = $_LANG['order_id_empty'];
        die($json->encode($result));
    }

    if ($user_id == 0)
    {
        /* 用户没有登录 */
        $result['error']   = 1;
        $result['message'] = $_LANG['login_please'];
        die($json->encode($result));
    }

    /* 检查订单是否属于该用户 */
    $order_user = $db->getOne("SELECT user_id FROM " .$ecs->table('order_info'). " WHERE order_id = '$order_id'");
    if (empty($order_user))
    {
        $result['error'] = 1;
        $result['message'] = $_LANG['order_exist'];
        die($json->encode($result));
    }
    else
    {
        if ($order_user != $user_id)
        {
            $result['error'] = 1;
            $result['message'] = $_LANG['no_priv'];
            die($json->encode($result));
        }
    }
    $message = return_to_cart($order_id);

    if ($message === true)
    {
        $result['error'] = 0;
        $result['message'] = '加入购物车成功';
        die($json->encode($result));
    }
    else
    {
        $result['error'] = 1;
        $result['message'] = $_LANG['order_exist'];
        die($json->encode($result));
    }

}
/* 保存订单详情收货地址 */
elseif ($action == 'save_order_address')
{
    include_once(ROOT_PATH .'includes/lib_transaction.php');

    $address = array(
        'consignee' => isset($_POST['consignee']) ? compile_str(trim($_POST['consignee']))  : '',
        'email'     => isset($_POST['email'])     ? compile_str(trim($_POST['email']))      : '',
        'address'   => isset($_POST['address'])   ? compile_str(trim($_POST['address']))    : '',
        'zipcode'   => isset($_POST['zipcode'])   ? compile_str(make_semiangle(trim($_POST['zipcode']))) : '',
        'tel'       => isset($_POST['tel'])       ? compile_str(trim($_POST['tel']))        : '',
        'mobile'    => isset($_POST['mobile'])    ? compile_str(trim($_POST['mobile']))     : '',
        'sign_building' => isset($_POST['sign_building']) ? compile_str(trim($_POST['sign_building'])) : '',
        'best_time' => isset($_POST['best_time']) ? compile_str(trim($_POST['best_time']))  : '',
        'order_id'  => isset($_POST['order_id'])  ? intval($_POST['order_id']) : 0
        );
    if (save_order_address($address, $user_id))
    {
        ecs_header('Location: user.php?act=order_detail&order_id=' .$address['order_id']. "\n");
        exit;
    }
    else
    {
        ecs_header('Location: user.php?act=order_detail&order_id=' .$address['order_id']. "\n");
    }
}

/* 我的红包列表 */
elseif ($action == 'bonus')
{
    include_once(ROOT_PATH .'includes/lib_transaction.php');

    $page = isset($_REQUEST['page']) ? intval($_REQUEST['page']) : 1;
    $record_count = $db->getOne("SELECT COUNT(*) FROM " .$ecs->table('user_bonus'). " WHERE user_id = '$user_id'");

    $pager = get_pager('user.php', array('act' => $action), $record_count, $page);
    $bonus = get_user_bouns_list($user_id, $pager['size'], $pager['start']);

    $smarty->assign('pager', $pager);
    $smarty->assign('bonus', $bonus);
    $smarty->display('user_transaction.dwt');
}
/* ajax 发送验证邮件 */
elseif ($action == 'send_hash_mail')
{
    include_once(ROOT_PATH .'includes/cls_json.php');
    include_once(ROOT_PATH .'includes/lib_passport.php');
    $json = new JSON();

    $result = array('error' => 0, 'message' => '', 'content' => '');

    if ($user_id == 0)
    {
        /* 用户没有登录 */
        $result['error']   = 1;
        $result['message'] = $_LANG['login_please'];
        die($json->encode($result));
    }

    if (send_regiter_hash($user_id))
    {
        $result['message'] = $_LANG['validate_mail_ok'];
        die($json->encode($result));
    }
    else
    {
        $result['error'] = 1;
        $result['message'] = $GLOBALS['err']->last_message();
    }

    die($json->encode($result));
}

/* 刮蛋乐菜单页 */
elseif ($action == 'guadanle')
{
    include_once(ROOT_PATH . 'includes/lib_transaction.php');
    $user_id = $_SESSION['user_id'];
    $page = isset($_REQUEST['page']) ? intval($_REQUEST['page']) : 1;

    //分页函数
    $sql =  "SELECT COUNT(*) " .
            " FROM " . $ecs->table('guadanle') . " AS gd " .
            " LEFT JOIN " . $ecs->table('goods') . " AS g " .
                " ON g.goods_sku = gd.goods_sku " .
            " WHERE gd.user_id = '$user_id' ORDER BY gd.start_time DESC";
    $record_count = $db->getOne($sql);
    $pager = get_pager('user.php', array('act' => $action), $record_count, $page);

    /* 获取用户兑换过的刮蛋乐赠品 */
    $sql =  "SELECT gd.id, gd.cdkey, gd.end_time, gd.exchange, g.goods_thumb, g.goods_id " .
            " FROM " . $ecs->table('guadanle') . " AS gd " .
            " LEFT JOIN " . $ecs->table('goods') . " AS g " .
                " ON g.goods_sku = gd.goods_sku " .
            " WHERE gd.user_id = '$user_id' ORDER BY gd.start_time DESC LIMIT $pager[start], $pager[size]";
    $exchange = $db->getAll($sql);


    $smarty->assign('pager', $pager);
    $smarty->assign('exchange', $exchange);
    $smarty->assign('time', time());
    $smarty->display('user_transaction.dwt');
}

elseif ($action == 'track_packages')
{
    include_once(ROOT_PATH . 'includes/lib_transaction.php');
    include_once(ROOT_PATH .'includes/lib_order.php');

    $page = isset($_REQUEST['page']) ? intval($_REQUEST['page']) : 1;

    $orders = array();

    $sql = "SELECT order_id,order_sn,invoice_no,shipping_id FROM " .$ecs->table('order_info').
            " WHERE user_id = '$user_id' AND shipping_status = '" . SS_SHIPPED . "'";
    $res = $db->query($sql);
    $record_count = 0;
    while ($item = $db->fetch_array($res))
    {
        $shipping   = get_shipping_object($item['shipping_id']);

        if (method_exists ($shipping, 'query'))
        {
            $query_link = $shipping->query($item['invoice_no']);
        }
        else
        {
            $query_link = $item['invoice_no'];
        }

        if ($query_link != $item['invoice_no'])
        {
            $item['query_link'] = $query_link;
            $orders[]  = $item;
            $record_count += 1;
        }
    }

    $pager  = get_pager('user.php', array('act' => $action), $record_count, $page);
    $smarty->assign('pager',  $pager);
    $smarty->assign('action',  $action);
    $smarty->assign('orders', $orders);
    $smarty->display('user_transaction.dwt');
}

/* 我的优惠券 */
elseif ($action == 'coupon')
{
    $smarty->assign('action',  $action);
    /*获取优惠卷信息*/
    $user_id = $_SESSION['user_id'] ? $_SESSION['user_id'] : 0;
    $time = time();
    $sql =  " SELECT c.* , ct.* FROM ".$GLOBALS['ecs']->table('coupon')."AS c".
            " LEFT JOIN ".$GLOBALS['ecs']->table('coupon_type')."AS ct ON c.type_id = ct.type_id ".
            " WHERE c.user_id = '$user_id' ".
            " ORDER BY ct.type_name ASC";
    $coupon = $GLOBALS['db']->getAll($sql);
    // dump($coupon);
    // exit();
    /*重组数据*/
    foreach ($coupon as $key => $value) {
        /*过期优惠卷*/
        if ($value['end_time']<time()&&$value['is_use']=='0') {
           $couponOld[$key]=$value;
           $couponOld[$key]['start_time_format'] = date('Y-m-d',$coupon[$key]['start_time']);
           $couponOld[$key]['end_time_format']   = date('Y-m-d',$coupon[$key]['end_time']);
        }
        /*已使用优惠卷*/
        if ($value['is_use']=='1') {
           $couponUse[$key]=$value;
        }
        /*未使用优惠卷*/
        if ($value['is_use']=='0'&&$value['end_time']>time()&&$value['start_time']<time()) {
            $couponIsUse[$key]=$value;
            $couponIsUse[$key]['start_time_format'] = date('Y-m-d',$coupon[$key]['start_time']);
            $couponIsUse[$key]['end_time_format']   = date('Y-m-d',$coupon[$key]['end_time']);
            $couponIsUse[$key]['is_due']            = ($coupon[$key]['end_time']-$time)<172800?1:0;
        }
    }

    if (!empty($couponOld)) {
        $smarty->assign('couponOldCount', count($couponOld));
        $smarty->assign('couponOld', $couponOld);
    }
    if (!empty($couponUse)) {
        $smarty->assign('couponUseCount', count($couponUse));
        $smarty->assign('couponUse', $couponUse);
    }
    if (!empty($couponIsUse)) {
        $smarty->assign('couponIsUseCount', count($couponIsUse));
        $smarty->assign('couponIsUse', $couponIsUse);
    }
    $smarty->display('user_transaction.dwt');
}


elseif ($action == 'act_transform_points')
{
    $rule_index = empty($_POST['rule_index']) ? '' : trim($_POST['rule_index']);
    $num = empty($_POST['num']) ? 0 : intval($_POST['num']);


    if ($num <= 0 || $num != floor($num))
    {
        show_message($_LANG['invalid_points'], $_LANG['transform_points'], 'user.php?act=transform_points');
    }

    $num = floor($num); //格式化为整数

    $bbs_key = substr($rule_index, 1);
    $rule_key = substr($rule_index, 0, 1);

    $max_num = 0;

    /* 取出用户数据 */
    $sql = "SELECT user_name, user_id, pay_points, rank_points FROM " . $ecs->table('users') . " WHERE user_id='$user_id'";
    $row = $db->getRow($sql);
    $bbs_points = $user->get_points($row['user_name']);
    $points_name = $user->get_points_name();

    $rule = array();
    if ($_CFG['points_rule'])
    {
        $rule = unserialize($_CFG['points_rule']);
    }
    list($from, $to) = explode(':', $rule[$rule_index]);

    $max_points = 0;
    switch ($rule_key)
    {
        case TO_P :
            $max_points = $bbs_points[$bbs_key];
            break;
        case TO_R :
            $max_points = $bbs_points[$bbs_key];
            break;
        case FROM_P :
            $max_points = $row['pay_points'];
            break;
        case FROM_R :
            $max_points = $row['rank_points'];
    }

    /* 检查积分是否超过最大值 */
    if ($max_points <=0 || $num > $max_points)
    {
        show_message($_LANG['overflow_points'], $_LANG['transform_points'], 'user.php?act=transform_points' );
    }

    switch ($rule_key)
    {
        case TO_P :
            $result_points = floor($num * $to / $from);
            $user->set_points($row['user_name'], array($bbs_key=>0 - $num)); //调整论坛积分
            log_account_change($row['user_id'], 0, 0, 0, $result_points, $_LANG['transform_points'], ACT_OTHER);
            show_message(sprintf($_LANG['to_pay_points'],  $num, $points_name[$bbs_key]['title'], $result_points), $_LANG['transform_points'], 'user.php?act=transform_points');

        case TO_R :
            $result_points = floor($num * $to / $from);
            $user->set_points($row['user_name'], array($bbs_key=>0 - $num)); //调整论坛积分
            log_account_change($row['user_id'], 0, 0, $result_points, 0, $_LANG['transform_points'], ACT_OTHER);
            show_message(sprintf($_LANG['to_rank_points'], $num, $points_name[$bbs_key]['title'], $result_points), $_LANG['transform_points'], 'user.php?act=transform_points');

        case FROM_P :
            $result_points = floor($num * $to / $from);
            log_account_change($row['user_id'], 0, 0, 0, 0-$num, $_LANG['transform_points'], ACT_OTHER); //调整商城积分
            $user->set_points($row['user_name'], array($bbs_key=>$result_points)); //调整论坛积分
            show_message(sprintf($_LANG['from_pay_points'], $num, $result_points,  $points_name[$bbs_key]['title']), $_LANG['transform_points'], 'user.php?act=transform_points');

        case FROM_R :
            $result_points = floor($num * $to / $from);
            log_account_change($row['user_id'], 0, 0, 0-$num, 0, $_LANG['transform_points'], ACT_OTHER); //调整商城积分
            $user->set_points($row['user_name'], array($bbs_key=>$result_points)); //调整论坛积分
            show_message(sprintf($_LANG['from_rank_points'], $num, $result_points, $points_name[$bbs_key]['title']), $_LANG['transform_points'], 'user.php?act=transform_points');
    }
}
elseif ($action == 'act_transform_ucenter_points')
{
    $rule = array();
    if ($_CFG['points_rule'])
    {
        $rule = unserialize($_CFG['points_rule']);
    }
    $shop_points = array(0 => 'rank_points', 1 => 'pay_points');
    $sql = "SELECT user_id, user_name, pay_points, rank_points FROM " . $ecs->table('users')  . " WHERE user_id='$user_id'";
    $row = $db->getRow($sql);
    $exchange_amount = intval($_POST['amount']);
    $fromcredits = intval($_POST['fromcredits']);
    $tocredits = trim($_POST['tocredits']);
    $cfg = unserialize($_CFG['integrate_config']);
    if (!empty($cfg))
    {
        $_LANG['exchange_points'][0] = empty($cfg['uc_lang']['credits'][0][0])? $_LANG['exchange_points'][0] : $cfg['uc_lang']['credits'][0][0];
        $_LANG['exchange_points'][1] = empty($cfg['uc_lang']['credits'][1][0])? $_LANG['exchange_points'][1] : $cfg['uc_lang']['credits'][1][0];
    }
    list($appiddesc, $creditdesc) = explode('|', $tocredits);
    $ratio = 0;

    if ($exchange_amount <= 0)
    {
        show_message($_LANG['invalid_points'], $_LANG['transform_points'], 'user.php?act=transform_points');
    }
    if ($exchange_amount > $row[$shop_points[$fromcredits]])
    {
        show_message($_LANG['overflow_points'], $_LANG['transform_points'], 'user.php?act=transform_points');
    }
    foreach ($rule as $credit)
    {
        if ($credit['appiddesc'] == $appiddesc && $credit['creditdesc'] == $creditdesc && $credit['creditsrc'] == $fromcredits)
        {
            $ratio = $credit['ratio'];
            break;
        }
    }
    if ($ratio == 0)
    {
        show_message($_LANG['exchange_deny'], $_LANG['transform_points'], 'user.php?act=transform_points');
    }
    $netamount = floor($exchange_amount / $ratio);
    include_once(ROOT_PATH . './includes/lib_uc.php');
    $result = exchange_points($row['user_id'], $fromcredits, $creditdesc, $appiddesc, $netamount);
    if ($result === true)
    {
        $sql = "UPDATE " . $ecs->table('users') . " SET {$shop_points[$fromcredits]}={$shop_points[$fromcredits]}-'$exchange_amount' WHERE user_id='{$row['user_id']}'";
        $db->query($sql);
        $sql = "INSERT INTO " . $ecs->table('account_log') . "(user_id, {$shop_points[$fromcredits]}, change_time, change_desc, change_type)" . " VALUES ('{$row['user_id']}', '-$exchange_amount', '". gmtime() ."', '" . $cfg['uc_lang']['exchange'] . "', '98')";
        $db->query($sql);
        show_message(sprintf($_LANG['exchange_success'], $exchange_amount, $_LANG['exchange_points'][$fromcredits], $netamount, $credit['title']), $_LANG['transform_points'], 'user.php?act=transform_points');
    }
    else
    {
        show_message($_LANG['exchange_error_1'], $_LANG['transform_points'], 'user.php?act=transform_points');
    }
}
/* 清除商品浏览历史 */
elseif ($action == 'clear_history')
{
    setcookie('ECS[history]',   '', 1);
}

/* 用户消息提醒 */
elseif ($action == 'message'){
    include_once(ROOT_PATH . 'includes/lib_clips.php');
    $smarty->assign('lang',  $_LANG);
    $smarty->assign('action',  $action);
    $page = isset($_REQUEST['page']) ? intval($_REQUEST['page']) : 1;
    $record_count = $db->getOne("SELECT COUNT(*) FROM " . $ecs->table('user_message') . " WHERE user_id = '$user_id'");
    $pager  = get_pager('user.php', array('act' => $action), $record_count, $page);
    $message = get_user_message($user_id, $pager['size'], $pager['start']);

    $smarty->assign('pager',  $pager);
    $smarty->assign('message',  $message);

    $smarty->display('user_clips.dwt');

}


/* AJAX用户消息提醒 */
elseif ($action == 'ajax_message')
{
    $sql = "SELECT * FROM " . $ecs->table('user_message')  . " WHERE ischeck = 0 AND user_id='$user_id'";
    include_once('includes/cls_json.php');
    $json = new JSON;
    die($json->encode($db->getAll($sql)));
}
/* AJAX关闭用户消息提醒 */
elseif ($action == 'ajax_close_message')
{
    $id = isset($_REQUEST['message_id']) ? intval($_REQUEST['message_id']) : 0;
    if($id){
        $sql = "UPDATE " . $ecs->table('user_message')  . " SET ischeck=1 WHERE ischeck = 0 AND id=$id";
        echo $db->query($sql);
    }else{
        echo 0;
    }
}

/* 用户手机验证页面 */
elseif ($action == 'mobile_validated'){
    include_once(ROOT_PATH . 'includes/lib_clips.php');
    $sql = "SELECT * FROM " . $ecs->table('users')  . " where user_id = $user_id";
    $info = $db->getRow($sql);
    $smarty->assign('info', $info);
    $smarty->display('user_validated.dwt');
}
/* 处理用户手机验证信息 */
elseif ($action == 'validated_mobile'){
    include_once(ROOT_PATH . 'includes/lib_passport.php');
    if($_SESSION['captcha_time']+600 > time()){
        $code = rand('100000','999999');
        $captcha = intval($_POST['captcha']);
        $mobile = intval($_POST['mobile']);
        if($_SESSION['captcha'] != $captcha && $_SESSION['mobile'] != $mobile){
            show_message('验证码出错，请重新输入！','返回','user.php?act=mobile_validated');
        }else{
            $sql = "UPDATE " . $ecs->table('users')  . " SET is_mobile_validated = 1 WHERE user_id = $user_id";
            $db->query($sql);
            show_message('手机验证成功，跳转用户中心！','返回用户中心','user.php');
        }
    }
}

/* ajax找回密码验证手机验证码 */
elseif ($action == 'rp_validate_mobile') {
    include_once('includes/cls_json.php');
    $json = new JSON;
    $captcha_number =  !empty(is_numeric($_POST['captcha_number'])) ? intval(trim($_POST['captcha_number'])) : '';
    $return = array('error' =>'0' ,'message'=>'','content'=>'' );
    //判断验证码是否一样
    if($captcha_number == $_SESSION['resetCaptcha']){
        $smarty->assign('action','resetPassword');
        $smarty->assign('captcha',$captcha_number);
        $return['error'] = 0;
        $return['message'] = "验证码正确";
        $return['content'] = $smarty->fetch('library/ajax_loading.lbi');
    }else{
        $return['error'] = 506;
        $return['message'] = "验证码错误";
    }

    die($json->encode($return));
}

/*ajax找回密码 手机重置密码*/

elseif ($action == 'ajax_change_password') {

    include_once('includes/cls_json.php');
    $json = new JSON;
    $password = !empty($_POST['password'])?$_POST['password']:'';
    $captcha  = !empty($_POST['captcha'])?$_POST['captcha']:'';
    $user_id  = !empty($captcha)?$_SESSION['user_id'.$captcha]:'0';
    $return = array('error' => '0','message'=>'','content'=>'' );

    if (empty($user_id)||empty($password)) {
        $return['error'] = '302';
        $return['message'] = '页面已过期';
        die($json->encode($return));
    }


    /*修改密码*/
    $ec_salt = rand(1000,9999);
    $user = $db->query('UPDATE ' . $GLOBALS['ecs']->table("users") . "SET `password`='".MD5(MD5($password). $ec_salt)."',`ec_salt`='". $ec_salt."' WHERE user_id = '" . $user_id . "'");
    if ($user) {
        $smarty->assign('action','resetSuccess');
        $return['message'] = '修改成功';
        $return['content'] = $smarty->fetch('library/ajax_loading.lbi');
        die($json->encode($return));
    }else{
        $return['error'] = '302';
        $return['message'] = '页面已过期';
        die($json->encode($return));
    }

}
/*邮箱重置密码*/
elseif ($action == 'email_change_password') {
    include_once('includes/cls_json.php');
    $json = new JSON;
    $password = !empty($_POST['password'])?$_POST['password']:'';
    $captcha  = !empty($_POST['captcha'])?$_POST['captcha']:'';
    $sql ='SELECT user_id FROM '.$ecs->table('users')."WHERE captcha = '$captcha'";
    $user_id = $db->getOne($sql);
    $return = array('error' => '0','message'=>'','content'=>'' );
    if (empty($user_id)||empty($password)) {
        $return['error'] = '302';
        $return['message'] = '页面已过期';
        $smarty->assign('action','reset_fail');
        $smarty->assign('ajax','1');
        $return['content'] = $smarty->fetch('email_result.dwt');
        die($json->encode($return));
    }
    /*修改密码*/
    $ec_salt = rand(1000,9999);
    $user = $db->query('UPDATE ' . $GLOBALS['ecs']->table("users") . "SET `password`='".MD5(MD5($password). $ec_salt)."',`ec_salt`='". $ec_salt."' WHERE user_id = '" . $user_id . "'");
    if ($user) {
        $sql = "UPDATE ".$ecs->table('users')."SET captcha = 0 WHERE user_id = '$user_id'";
        $db->query($sql);
        $smarty->assign('action','reset_password_success');
        $smarty->assign('ajax','1');
        $return['message'] = '修改成功';
        $return['content'] = $smarty->fetch('email_result.dwt');
        die($json->encode($return));
    }else{
        $return['error'] = '302';
        $return['message'] = '页面已过期';
        $smarty->assign('action','reset_fail');
        $smarty->assign('ajax','1');
        $return['content'] = $smarty->fetch('email_result.dwt');
        die($json->encode($return));
    }

}elseif($action == "my_recommend"){

    include_once(ROOT_PATH . 'includes/lib_transaction.php');
    
    //去拿用户信息
    $user_array = array();
    $sql = 'SELECT * FROM ' . $ecs->table('users') . ' WHERE user_id = '.$_SESSION['user_id'];
    $user_array = $db->getAll($sql);
    
    $one_user = array();
    
    if(!empty($user_array[0]['user_id'])){
        $user_array = $user_array[0];
        
        if($user_array['agent_rank']==2){
            //一级分销商判断
            $one_user = array();
            $sql = "select user_id,mobile_phone from ".$ecs->table('users'). " where user_id = ".$user_array['parent_uid']." and agent_rank = 1  ";
            $one_user = $db->getAll($sql);
            if(!empty($one_user[0]['user_id'])){
                $one_user = $one_user[0];
            }
        }
        
    }else{
        show_message("用户不存在");
    }
    
     $smarty->assign('one_user',$one_user);
     $smarty->assign('user',$user_array);
    
    $smarty->display('user_transaction.dwt');
}elseif($action == "my_recommend_action"){
    
    //一级分销商判断
    $binding_mobile = $_POST['recommend_mobile'];
    $one_user = array();
    $sql = "select user_id from ".$ecs->table('users'). " where mobile_phone = '".$binding_mobile."' and agent_rank = 1  ";
    $one_user = $db->getAll($sql);

    if(empty($one_user[0]['user_id'])){
        show_message("对方不是代理商用户");
    }
    $one_user = $one_user[0];
   //去拿用户信息
   $user_array = array();
   $sql = 'SELECT * FROM ' . $ecs->table('users') . ' WHERE user_id = '.$_SESSION['user_id'];
   $user_array = $db->getAll($sql);

   if(!empty($user_array[0]['user_id'])){
       $user_array = $user_array[0];

       if($user_array['agent_rank']!=100){
           show_message("只有普通用户才能使用此功能");
       }
       
       if($one_user['user_id']==$_SESSION['user_id']){
           show_message("不能绑定自己");
       }
       
       $sql="UPDATE ".$ecs->table('users'). "SET `agent2_time`=".time().",`agent_rank` = 2,`parent_uid` = ".$one_user['user_id']." WHERE user_id= '".$user_array['user_id']."'";
       $db->query($sql);
      
       show_message("已成功绑定");
   }else{
       show_message("用户不存在");
   }
   
}elseif($action == "my_distributor"){

    //去拿用户信息
    $user_array = array();
    $user_array = get_user_all_info();
    
    if(empty($user_array['user_id'])){
        show_message("用户不存在");
    }
    //那到他的下一级用户列表
    $user_list = array();
    $sql = 'SELECT users.user_id,users.user_name,users.agent2_time,users.mobile_phone,orders.all_price 
            FROM ' . $ecs->table('users') . ' as users 
            left join (select order1.user_id,SUM(order1.goods_amount) as all_price from '.$ecs->table('order_info').' as order1
                        left join ' . $ecs->table('users') . ' as users1 on users1.user_id = order1.user_id 
                        where order1.add_time >= users1.agent2_time and order1.order_status=5 and order1.shipping_status=2 and order1.pay_status = 2
                        group by order1.user_id) as orders on orders.user_id = users.user_id
            WHERE parent_uid = '.$user_array['user_id'] ." and agent_rank = 2";
    $user_list = $db->getAll($sql);
    //处理数据
    foreach ($user_list as $key => $val){
        if(empty($val['all_price'])){
            $user_list[$key]['all_price'] = 0;
        }
        $user_list[$key]['agent2_time'] = date("Y-m-d H:i:s",$user_list[$key]['agent2_time']);
    }

    $smarty->assign("user_list",$user_list);
    $smarty->assign("user_array",$user_array);
    
    $smarty->display('user_transaction.dwt');
    
}elseif ($action == "distributor_detailed"){
    
    //去拿用户信息
    $user_array = array();
    $user_array = get_user_all_info();
    
    if(empty($user_array['user_id'])){
        show_message("用户不存在");
    }
    
    $where = " AND orders.order_status = 5 AND orders.shipping_status = 2  AND orders.pay_status = 2 AND orders.add_time >= users.agent2_time ";
    if(!empty($_POST['time_select'])){
        if($_POST['time_select']==1){ //本月
            $time = strtotime(date("Y-m-01 H:i:s",time()));
            $where .= " and orders.add_time >= ".$time;
        }elseif ($_POST['time_select']==2){ //上个月
            $starttime = strtotime("-1 month",strtotime(date("Y-m-01 H:i:s",time())));
            $endtime = strtotime(date("Y-m-01 H:i:s",time()));
            $where .= " and orders.add_time >= ".$starttime." and orders.add_time < ".$endtime;
        }
        $smarty->assign("time_select",$_POST['time_select']);
    }
    
    //订单列表
    $order_list = array();
    $sql = 'SELECT orders.order_sn,orders.withdraw_status,users.user_id,users.user_name,users.mobile_phone,orders.goods_amount,orders.add_time
            FROM ' . $ecs->table('order_info') . ' as orders
            left join ' . $ecs->table('users') . ' as users on users.user_id = orders.user_id
            WHERE users.parent_uid = '.$user_array['user_id'] ." and users.agent_rank = 2 ".$where."
            order by orders.order_id DESC";
    $order_list = $db->getAll($sql);
    
    $withdraw_status_array = array("0"=>"未申请","1"=>"申请中","2"=>"已提现");
    
    //处理数据
    foreach ($order_list as $key => $val){
        $order_list[$key]['add_time'] = date("Y-m-d H:i:s",$order_list[$key]['add_time']);
        $order_list[$key]['withdraw_status'] = $withdraw_status_array[$val['withdraw_status']];
        //提成计算
        $order_list[$key]['commission_price'] = round($val['goods_amount']*COMMISSIONS_RATIO,2);
        
    }

    $smarty->assign("order_list",$order_list);
    
    $smarty->display('user_transaction.dwt');
    
}elseif ($action == "user_withdraw"){
    //提现逻辑
    $user_array = array();
    $user_array = get_user_all_info();
    
    if(empty($user_array['user_id'])){
        show_message("用户不存在");
    }
    //提现信息
    $order_list = array();
    $sql = 'SELECT orders.order_id
            FROM ' . $ecs->table('order_info') . ' as orders
            left join ' . $ecs->table('users') . ' as users on users.user_id = orders.user_id
            WHERE users.parent_uid = '.$user_array['user_id'] ." and users.agent_rank = 2 and orders.withdraw_status=0 and orders.order_status=5 and orders.shipping_status=2 and orders.pay_status=2 and orders.add_time >= users.agent2_time ";
    $order_list = $db->getAll($sql);
    
    if(count($order_list)<=0){
        show_message("暂时没有可提现的订单");
    }
    foreach ($order_list as $key => $val){
        //将订单的提现状态修改为已申请
        $sql = "UPDATE ". $ecs->table('order_info') . " SET withdraw_status = 1,commissions_ratio = ".COMMISSIONS_RATIO." WHERE order_id = ".$val['order_id'];
        $db->query($sql);
        
        $sql = "INSERT INTO " .$ecs->table('withdraw_log'). " (order_id, user_id, status,remark,inputtime)" .
            "VALUES ('$val[order_id]','$_SESSION[user_id]',1, '用户在前台操作，申请提现', ".time().")";
        $db->query($sql);
        
    }
    show_message("已成功申请提现");
}

?>
